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

12

list[s] 是一个字符串。为什么它不起作用?

出现以下错误:

TypeError: 列表索引必须是整数,而不是字符串

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

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

22
请勿使用“list”作为名称,它是 Python 内置函数的一个影子。 - Anzel
5个回答

14
当你遍历一个列表时,循环变量接收的是实际的列表元素,而不是它们的索引。因此,在你的例子中,s 是一个字符串(首先是 abc,然后是 def)。
看起来你想要做的基本上是这样的:
orig_list = ['abc', 'def']
map_list = [(el, 1) for el in orig_list]

这里使用了Python中的一个叫做列表推导式的结构。


6

不要使用名称为list的列表。以下我使用了mylist

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

for s in mylist:循环遍历mylist中的元素,并将其赋值给变量s。例如,第一次迭代时s的值为'abc',第二次迭代时s的值为'def'。因此,不能使用s作为索引来访问mylist[s]

相反,可以简单地执行以下操作:

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

2

应该是这样的:

for s in my_list:     # here s is element  of list not index of list
    t = (s, 1)
    map_list.append(t)

i think you want:

for i,s in enumerate(my_list):  # here i is the index and s is the respective element
    t = (s, i)
    map_list.append(t)

enumerate 函数会返回索引和元素

注意:使用 list 作为变量名是不好的习惯。这是内置函数。


2
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]
>>> 

这正是您想要的。

如果您不想到达每个元素,则:

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

输出:

>>> 
[0, 1]
>>> 

28
我给出了负面评价是因为这篇文章没有解释原始代码为什么无法正常运行,也没有指出原帖作者对问题的理解存在哪些错误。 - SethMMorton

0

for s in list 会产生列表的项目而不是它们的索引。所以在第一次循环中,s 将是 'abc',然后是 'def''abc' 只能是字典的键,而不是列表索引。

在使用 t 的行中,通过索引获取项目在 Python 中是多余的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接