簡體   English   中英

每當項目出現在第一個列表中時,將第二個列表的內容加在一起

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM