如何删除列表中的重复“键”并计算值的平均值

时间:2018-04-23 18:57:23

标签: python list dictionary

我有一个列表列表,我需要获取具有相同“键”的元素的平均值(列表中位置[0]中的元素)。

[[('a', 'b'), 1], [('b', 'c'), 2], [('a', 'b'), 5]]

我想显示[('a', 'b'), 3], [('b', 'c'), 2]]。你能帮忙吗?

谢谢!

3 个答案:

答案 0 :(得分:8)

你不能在这里使用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))将均值计算为整数(舍入为最小值)。如果你想要精确的浮点值,可以使用sum(v)/len(v)表示python 2或statistics.mean表示python 3,或者jpp注意None

答案 1 :(得分:3)

以下是使用标准库中提供的itertools.groupbystatistics.mean的解决方案。

from itertools import groupby
from statistics import mean
from operator import itemgetter

lst = [[('a', 'b'), 1], [('b', 'c'), 2], [('a', 'b'), 5]]

grouper = groupby(sorted(lst), key=itemgetter(0))
res = ((i, mean(map(itemgetter(1), j))) for i, j in grouper)

print(list(res))

# [(('a', 'b'), 3), (('b', 'c'), 2)]

<强>解释

  • sorted集合创建迭代器。必须进行排序itertools.groupby
  • 使用列表推导返回元组列表。
  • 使用statistics.mean计算groupby元素的第二个元素的平均值,我们可以通过operator.itemgetter提取这些元素。

答案 2 :(得分:3)

为了更多选项,您还可以在pandas中groupbymean

import pandas as pd

df = pd.DataFrame(s)
meaned_df = df.groupby(0).mean()

        1
0        
(a, b)  3
(b, c)  2

然后使用to_dict()进行格式化:

>>> meaned_df.to_dict()[1]

[{('a', 'b'): 3}, {('b', 'c'): 2}]

当然你可以把它变成一个单行:)

>> pd.DataFrame(s).groupby(0).mean().to_dict()[1]

输出

[{('a', 'b'): 3}, {('b', 'c'): 2}]