我有三个词典(或更多):
A = {'a':1,'b':2,'c':3,'d':4,'e':5}
B = {'b':1,'c':2,'d':3,'e':4,'f':5}
C = {'c':1,'d':2,'e':3,'f':4,'g':5}
Run Code Online (Sandbox Code Playgroud)
如何获取三个词典中每个键的平均值的字典?
例如,给定上面的词典,输出将是:
{'a':1/1, 'b':(2+1)/2, 'c':(3+2+1)/3, 'd':(4+3+2)/3, 'e':(5+4+3)/3, 'f':(5+4)/2, 'g':5/1}
Run Code Online (Sandbox Code Playgroud)
小智 7
我使用 Counter 来解决这个问题。请尝试以下代码:)
from collections import Counter
A = {'a':1,'b':2,'c':3,'d':4,'e':5}
B = {'b':1,'c':2,'d':3,'e':4,'f':5}
C = {'c':1,'d':2,'e':3,'f':4,'g':5}
sums = Counter()
counters = Counter()
for itemset in [A, B, C]:
sums.update(itemset)
counters.update(itemset.keys())
ret = {x: float(sums[x])/counters[x] for x in sums.keys()}
print ret
Run Code Online (Sandbox Code Playgroud)
您可以使用Pandas,如下所示:
import pandas as pd
df = pd.DataFrame([A,B,C])
answer = dict(df.mean())
print(answer)
Run Code Online (Sandbox Code Playgroud)