list[s]
是一个字符串。为什么它不起作用?
出现以下错误:
TypeError: 列表索引必须是整数,而不是字符串
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]
这里使用了Python中的一个叫做列表推导式的结构。
不要使用名称为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)]
应该是这样的:
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 作为变量名是不好的习惯。这是内置函数。
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
会产生列表的项目而不是它们的索引。所以在第一次循环中,s
将是 'abc'
,然后是 'def'
。 'abc'
只能是字典的键,而不是列表索引。
在使用 t
的行中,通过索引获取项目在 Python 中是多余的。