2016-02-02 38 views
0

我有兩個列表:標籤和權重(這些排列在一起:weight [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),它將擺脫重複的標籤,但這就是我所能做的一切。

任何想法如何做到這一點?

+3

請讓你的問題更清晰,提供投入和預期產出和到目前爲止你已經嘗試了什麼! –

+0

模式:使用計數器或'zip()'遍歷'weight'列表。使用標籤作爲關鍵字和權重列表構建一個字典作爲值。 – dsh

+0

好的,我已經編輯澄清! –

回答

1

使用字典(如果想簡化代碼,則使用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 
1

作爲一種替代方法,你可以利用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

0

我推薦在這種情況下使用字典,因爲平行列表很容易出現錯位。這裏是一個使用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 
0

運用collectionsdefaultdict

>>> 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 
相關問題