[英]append adding contents to first list item, not adding new items to list
[英]Adding together the contents of a second list whenever an item appears in a first list
我有两个列表:标签和权重(这些排列在一起:weight [i]用于tag [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']
会返回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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.