2017-05-26 80 views

回答

1
from collections import Counter 
a = ['a','b','a'] 
b = [200,300,300] 
c = Counter() 
for i, j in zip(a, b): 
    c[i] += j 
print(c) 
+0

這更像是一個defaultdict方法。使用計數器,使用'c.update({i:j})'是不是更典型? –

+0

@ChrisJohnson:我一直使用'defaultdict'方法;我不確定哪一個更習慣。 – GWW

3
result = {} 
for k,v in zip (['a','b','a'], [200,300,300]): 
    result[k] = result.get(k,0) + v 
print result 
-1

一種方式做到這一點是像下面,通過避免拉鍊功能

aggregateDict = {} 
a= ['a', 'b', 'a'] 
b=[200, 300, 200] 
for i in range(len(a)): 
    aggregateDict[a[i]] = aggregateDict.get(a[i], 0) + b[i] 

輸出將是

{'a': 400, 'b': 300} 
+0

對於這種情況''zip'好得多 –

+0

@AzatIbrakov我認爲zip函數比range()有更多開銷。 Zip會創建一個元組的臨時複合容器列表,所以從內存效率和時間複雜度來看這並不好。 – manu

+0

如果您使用的是Python 3,那麼'zip'會創建迭代,所以沒有內存問題,在Python 2中您應該使用['itertools.izip'](https://docs.python.org/2 /library/itertools.html#itertools.izip) –

0

我假設一個清晰的方式(每Python's Zen)實現您的目標是:

from __future__ import print_function 

a = ['a','b','a'] 
b = [200,300,300] 
d = dict() 

for place, key in enumerate(a): 
    try: 
     d[key] += b[place] 
    except KeyError: 
     d[key] = b[place] 
print(d) 

哪個給你的預期輸出:

{ 'A':500, 'B':300}

0

你只需要遍歷的郵政編碼爲鍵和值,並把他們在字典中。

a = ['a','b','a'] 
b = [200,300,300] 

for key, val in zip(a,b): 
    if key in combined_dict: 
     combined_dict[key] += val 
    else: 
     combined_dict[key] = val 

print(combined_dict) 
=> {'a': 500, 'b': 300}