类型错误:列表索引必须是整数,而不是str Python

2024-04-26 12:13:48 发布

您现在位置:Python中文网/ 问答频道 /正文

list[s]是一个字符串。为什么这不管用?

出现以下错误:

TypeError: list indices must be integers, not str

list = ['abc', 'def']
map_list = []

for s in list:
  t = (list[s], 1)
  map_list.append(t)

Tags: integers字符串inmapfordef错误not
3条回答

不要对列表使用名称list。我使用了下面的mylist

for s in mylist:
    t = (mylist[s], 1)

for s in mylist:mylist的元素分配给s,即s在第一次迭代中使用值“abc”,在第二次迭代中使用值“def”。因此,s不能用作mylist[s]中的索引。

相反,只要做:

for s in lists:
    t = (s, 1)
    map_list.append(t)
print map_list
#[('abc', 1), ('def', 1)]

当您在列表上迭代时,循环变量接收实际的列表元素,而不是它们的索引。因此,在您的示例中,s是一个字符串(首先是abc,然后是def)。

看起来你要做的基本上是:

orig_list = ['abc', 'def']
map_list = [(el, 1) for el in orig_list]

这是使用一个名为list comprehension的Python构造。

list1 = ['abc', 'def']
list2=[]
for t in list1:
    for h in t:
        list2.append(h)
map_list = []        
for x,y in enumerate(list2):
    map_list.append(x)
print (map_list)

输出:

>>> 
[0, 1, 2, 3, 4, 5]
>>> 

这正是你想要的。

If you dont want to reach each element then:

list1 = ['abc', 'def']
map_list=[]
for x,y in enumerate(list1):
    map_list.append(x)
print (map_list)

输出:

>>> 
[0, 1]
>>> 

相关问题 更多 >