如何计算列表中每三个值的平均值

How to calculate mean of every three values of a list

我有一个列表:

first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

我想要另一个具有三个值的平均值的列表,因此新列表是:

new = [2,5,8,11,14,17]

新列表中只有 6 个值,因为第一个列表中只有 18 个元素。

我正在寻找一种优雅的方法,以最少的步骤完成一个大列表。

使用 numpy,您可以将包含 18 个元素的列表重塑为形状 (6, 3) 的数组,然后对行

取平均值
import numpy as np
a = np.array(first)

>>> a.reshape(-1, 3)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15],
       [16, 17, 18],

>>> a.reshape(-1, 3).mean(axis=1)
array([ 2.,  5.,  8., 11., 14., 17.])

np.reshape(-1, 3) 中使用 -1 实际上允许您将这种方法用于任何大小为 3 的倍数的数组,它会自动适当地调整第一个维度的大小

您可以使用在 3 个间隔

中迭代的 for 循环获取 first 的一部分
import statistics

new = [statistics.mean(first[i:i + 3]) for i in range(0, len(first), 3)]
print(new) # [2, 5, 8, 11, 14, 17]

这是另一个解决方案,它使用 statistics.mean() 来获取列表中每三个数字的每个块的平均值。

>>> from statistics import mean
>>> first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
>>> [mean(x) for x in zip(*[iter(first)] * 3)]
[2, 5, 8, 11, 14, 17]

这是一个使用 pandasgroupby 的解决方案:

import pandas as pd

ser = pd.Series(first)
ser.groupby(ser.index//3).mean()

0     2
1     5
2     8
3    11
4    14
5    17
dtype: int64