列表索引必须为整数,而不是字符串
我有两种列表:一个是名字列表,另一个是分数列表。我想把这些分数合并到一个已经存在的列表里。
但是我总是遇到“列表索引必须是整数,而不是字符串”的错误。
name1= [jim, bob, john, smith]
score1= [4,7,3,11]
name2= [bob, cahterine, jim, will, lucy]
score2= [6,12,7,1,4]
我想要的结果是:
name1 = [jim, bob, john, smith, catherine, will, lucy]
score2 = [11, 13 ,3 ,11 ,12 ,1 ,4]
def merge(name1,score1, name2,score2):
for i in name2:
if i in name1:
indexed= name1.index(i)
score2[i] =score1[int(indexed)]+score2[i]
if i not in name1:
name1.append(i)
score1.append(score2[(name1.index(i))])
5 个回答
相信错误信息,它会告诉你问题到底出在哪里。当你看到 score2[i]
时,问问自己“i到底是什么?”
在这个情况下,i 是 name2 中的一个元素。虽然你的示例代码显示的是 [bob, cahterine, jim, will, lucy]
,我猜这些都是字符串,也就是一串文字。
你有一些分数,这些分数是和名字关联在一起的。这说明你用错了数据结构。具体来说,这些数字代表的是你要加起来的分数,或者更准确地说,是要统计的分数。
Python里有一个内置的工具可以处理这个。
from collections import Counter
results_1 = Counter(jim = 4, bob = 7, john = 3, smith = 11)
results_2 = Counter(bob = 6, catherine = 12, jim = 7, will = 1, lucy = 4)
results_1 + results_2 # yes, it's really this easy.
至于你的错误信息,它的意思就是字面上的意思,@BryanOakley已经详细解释过了。但我需要强调的是,在编程中,你必须精确、一致,并且时刻关注细节。养成好习惯可以避免这些错误,因为你会时刻思考自己在做什么,以及这到底意味着什么。遵循一些风格规范也会有帮助:
给你的迭代器起个和它实际包含的内容相关的名字。因为在Python中,遍历一个列表实际上是获取列表中的项目(而不是整数索引),所以用一个能表示实际列表项的名字,而不是像
i
这样平淡无奇的名字。给你的列表和其他容器起个复数的名字,这样你的代码自然就能描述发生了什么。因此,可以写成
for name in names:
。
我提到“关注细节”是因为:
当你发布代码时,不要手动输入;直接复制粘贴,这样我们才能准确看到你写的是什么。
拼写很重要。打错字会造成麻烦(比如
cahterine
)。字符串要用引号括起来。不要把字符串和变量名搞混了。
你可以考虑把这些数据放在Counter
类里,这个类是collections
模块的一部分。举个例子:
#! /usr/bin/env python
from collections import Counter
name1 = ["jim", "bob", "john", "smith"]
score1 = [4,7,3,11]
name2 = ["bob", "cahterine", "jim", "will", "lucy"]
score2 = [6,12,7,1,4]
first_set = dict(zip(name1, score1))
second_set = dict(zip(name2, score2))
print Counter(first_set) + Counter(second_set)
这样会输出以下内容:
Counter({'bob': 13, 'cahterine': 12, 'jim': 11, 'smith': 11, 'lucy': 4, 'john': 3, 'will': 1})
另外,可以看看Karl的回答,他把这个过程简化得更好。