Sor*_*ria 1 python dictionary list
我有一个列表列表,我需要取具有相同"键"的元素的平均值(列表中位置[0]中的元素).
[[('a', 'b'), 1], [('b', 'c'), 2], [('a', 'b'), 5]]
Run Code Online (Sandbox Code Playgroud)
我想要展示[('a', 'b'), 3], [('b', 'c'), 2]].你能帮忙吗?
谢谢!
你不能collections.Counter在这里使用,因为你需要记住同一个"密钥"有多少个整数.
我将使用a collections.defaultdict来记录列表中的整数值,使用元组作为键(在过程中合并它们).然后,扫描字典并计算平均值:
s = [[('a', 'b'), 1], [('b', 'c'), 2], [('a', 'b'), 5]]
import collections
c = collections.defaultdict(list)
for t,i in s:
c[t].append(i)
# at this point c contains: {('a', 'b'): [1, 5], ('b', 'c'): [2]}
result = [(t,sum(v)//len(v)) for t,v in c.items()]
print(result)
Run Code Online (Sandbox Code Playgroud)
打印:
[(('a', 'b'), 3), (('b', 'c'), 2)]
Run Code Online (Sandbox Code Playgroud)
(或作为字典: result = {t:sum(v)//len(v) for t,v in c.items()}
请注意,sum(v)//len(v)将均值计算为整数(舍入为最小值).如果你想要精确的浮点值,请使用sum(v)/float(len(v))python 2或sum(v)/len(v)python 3,或者注意jpp statistics.mean)