Python:将相同的整数值分组,然后求平均值

标签 python

我有大量数据,我想对相同整数的值进行分组,然后取平均值。

例如:

a = [0, 0.5, 1, 1.5, 2, 2.5]

我想按如下方式分组:

[0, 0.5] [1, 1.5] [2, 2.5]

...然后取平均值并将所有平均值放入一个新数组中。

最佳答案

假设您想按数字的整数值进行分组(因此数字向下舍入),类似这样的操作可能会起作用:

>>> a = [0, 0.5, 1, 1.5, 2, 2.5]
>>> groups = [list(g) for _, g in itertools.groupby(a, int)]
>>> groups
[[0, 0.5], [1, 1.5], [2, 2.5]]

然后平均变为:

>>> [sum(grp) / len(grp) for grp in groups]
[0.25, 1.25, 2.25]

这假设 a 已经排序,如您的示例所示。

引用号:itertools.groupby , list comprehensions .

关于Python:将相同的整数值分组,然后求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63919517/

相关文章:

python - 如何获取两个列表之间的所有唯一分配

python - MySQL在同一张表上加入两次给出了一半的结果

python - Django - 获取创建的最后一个对象,同时过滤器

python - 如何修复模块 'tensorflow' 没有属性 'get_default_session'

python - Pandas DataFrame 到列表列表的字典

python - 如何管理文件中的某些网址内容?

python - Tkinter:将标签延伸到列的边缘

python - 生成网格单元(占用网格)、为单元着色并删除 xlabel

python - python Tkinter,线程和循环

qlabel 中的 python 错误 : can not show . gif