TypeError:list indices必须是整数,而不是str Python

ker*_*chi 11 python mapreduce

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

出现以下错误:

TypeError:list indices必须是整数,而不是str

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

for s in list:
  t = (list[s], 1)
  map_list.append(t)
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 12

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

看起来你要做的事情基本上是这样的:

orig_list = ['abc', 'def']
map_list = [(el, 1) for el in orig_list]
Run Code Online (Sandbox Code Playgroud)

这是使用名为list comprehension的Python构造.


Ujj*_*wal 5

不要将名称list用于列表.我用过mylist下面的.

for s in mylist:
    t = (mylist[s], 1)
Run Code Online (Sandbox Code Playgroud)

for s in mylist:分配的元件mylist,以ss发生在第二次迭代中在第一次迭代的值"ABC"和"DEF".因此,s不能用作索引mylist[s].

相反,只需:

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


GLH*_*LHF 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)
Run Code Online (Sandbox Code Playgroud)

输出:

>>> 
[0, 1, 2, 3, 4, 5]
>>> 
Run Code Online (Sandbox Code Playgroud)

这正是您想要的。

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

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

输出:

>>> 
[0, 1]
>>> 
Run Code Online (Sandbox Code Playgroud)

  • 我投了反对票,因为这不能解释为什么原始代码不起作用或者OP理解中的错误在哪里。 (28认同)