list[s]
是一个字符串。为什么这不起作用?TypeError:列表索引必须是整数,而不是str Python
出现以下错误:
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)
list[s]
是一个字符串。为什么这不起作用?TypeError:列表索引必须是整数,而不是str Python
出现以下错误:
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)
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)
输出:
我downvoted蟒蛇的阴影,因为这并不能解释为什么原来的代码没有工作或OP的理解错误在哪里。 – SethMMorton
它应该是:
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作为变量名是不好的做法。其内置功能
请勿使用名称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构造。
for s in list
将产生列表中的项目而不是它们的索引。所以s
将为'abc'
第一个循环,然后 'def'
。 'abc'
只能是字典的关键字,而不是列表索引。
与t
一致通过索引获取项目在Python中是多余的。
请不要使用名单的名字,它的内置 – Anzel