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

时间:2013-03-06 23:52:54

标签: python list merge indexing

我有2种类型的名单:名称和分数,我正在尝试将这些分数组合在一起,以便将所有分数合并到现有列表中

我一直得到“列表索引必须是整数,而不是str”错误

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 个答案:

答案 0 :(得分:8)

您可能需要考虑将这些数据放在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's answer。它更加简化了这一点。

答案 1 :(得分:8)

您的分数在概念上名称相关联。这告诉您使用了错误的数据结构。特别是,数字表示您将要加起来的分数,或者更多的分数,计算

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)。

  • 字符串引用了它们。不要将字符串与变量名混淆。

答案 2 :(得分:5)

信任错误消息:它告诉您确切的问题所在。当你score2[i]时,问问自己“我是什么?”

在此上下文中,i是name2的元素。即使你的示例代码显示为[bob, cahterine, jim, will, lucy],我也猜测它们是字符串。

答案 3 :(得分:0)

我让这个工作,但我不知道你是否正在寻找这个?

name1= ['jim', 'bob', 'john', 'smith']
name2= ['bob', 'cahterine', 'jim', 'will', 'lucy']
score1= [4,7,3,11]
score2= [6,12,7,1,4]
def merge (name1,score1, name2,score2):
    for x in range(0,len(name1)):
        name2.append(name1[x])
    for x in range(0,len(score1)):
        score2.append(score1[x])
    print name2
    print score2
merge(name1,score1, name2,score2)

答案 4 :(得分:0)

def sum(index, name):
    score2[index] += score1[name1.index(name)]


name1= ["jim", "bob", "john", "smith"]
score1= [4,7,3,11]
name2= ["bob", "cahterine", "jim", "will", "lucy"]
score2= [6,12,7,1,4]

[sum(index, _name) for index, _name in enumerate(name2) if _name in name1 and _name in name2]

你可以使用列表推导