我有一个列表列表,我需要对具有相同“键”(列表中位置 [0] 的元素)的元素取平均值。
[[('a', 'b'), 1], [('b', 'c'), 2], [('a', 'b'), 5]]
我想显示 [('a', 'b'), 3], [('b', 'c'), 2]]。你能帮忙吗?
谢谢!
请您参考如下方法:
您不能在此处使用 collections.Counter,因为您需要记住同一个“键”有多少个整数。
我会使用 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)
打印:
[(('a', 'b'), 3), (('b', 'c'), 2)]
(或作为字典: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)
