![](/img/trans.png)
[英]'TypeError: list indices must be integers, not str' Python 3
[英]TypeError: list indices must be integers, not str Python
list[s]
是一个字符串。 为什么这不起作用?
出现以下错误:
TypeError:list indices必须是整数,而不是str
list = ['abc', 'def']
map_list = []
for s in list:
t = (list[s], 1)
map_list.append(t)
迭代列表时,循环变量接收实际的列表元素,而不是它们的索引。 因此,在您的示例中, s
是一个字符串(第一个abc
,然后是def
)。
看起来你要做的事情基本上是这样的:
orig_list = ['abc', 'def']
map_list = [(el, 1) for el in orig_list]
这是使用名为list comprehension的Python构造。
不要将名称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)]
它应该是:
for s in my_list: # here s is element of list not index of list
t = (s, 1)
map_list.append(t)
我想你想要:
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作为变量名是不好的做法。 它内置的功能
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]
>>>
for s in list
将生成for s in list
的项目而不是其索引。 所以s
对于第一个循环是'abc'
,然后是'def'
。 'abc'
只能是dict的关键,而不是列表索引。
在t
按索引获取项目的行在python中是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.