每当一个项目出现在第一个列表中时,将第二个列表的内容加在一起

Adding together the contents of a second list whenever an item appears in a first list

我有两个列表:标签和权重(它们排在一起:权重[i] 用于标签[i])。标签可以出现多次。所以,我要做的是将每个标签的所有权重加在一起,以获得每个标签的总权重。

列表如下所示

tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
weights = [100, 20, 45, 50, 75, 50]

我想要得到的是这样的:

tags = ['alternative', 'indie', 'jam rock', 'punk']
weights =[175, 70, 45, 50]

我试过使用各种循环,但我不知道如何正确地使用它。我一直在使用 .remove(i),它将去除重复的标签,但这就是我所能做的。

知道怎么做吗?

使用字典(如果您想简化代码,也可以使用 defaultdict)。

tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
weights = [100, 20, 45, 50, 75, 50]
d = {}
for tag, weight in zip(tags, weights):
    if tag in d:
        d[tag] += weight
    else:
        d[tag] = weight

new_tags = [tag for tag in sorted(d)] #if you want it in alphabetical order
new_weights = [d[tag] for tag in new_tags]
print new_tags
print new_weights

作为替代方法,您可以使用 Python 的 Counter,如下所示:

from collections import Counter

tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
weights = [100, 20, 45, 50, 75, 50]
totals = Counter()

for t, w in zip(tags, weights):
    totals[t] += w

print totals

这将显示以下输出:

Counter({'alternative': 175, 'indie': 70, 'punk': 50, 'jam rock': 45})

totals 可以像普通字典一样使用,例如print totals['indie'] 会 return 70.

我建议在这种情况下使用字典,因为平行列表很容易错位。这是一个使用 defaultdict 的示例,就像评论中建议的铁拳一样。

from collections import defaultdict
tagDict = defaultdict(int)
tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
weights = [100, 20, 45, 50, 75, 50]

for i in range(len(tags)):
    tagDict[tags[i]] += weights[i]

print tagDict

使用 collections 中的 defaultdict

>>> tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
>>> weights = [100, 20, 45, 50, 75, 50]
>>> 
>>> 
>>> from collections import defaultdict
>>> 
>>> d = defaultdict(int)
>>> 
>>> for k,v in zip(tags, weights):
        d[k] += v

>>> d
defaultdict(<class 'int'>, {'jam rock': 45, 'punk': 50, 'alternative': 175, 'indie': 70})
>>> 
>>> d['alternative']
175