如何计算列表的每三个值的平均值 [英] How to calculate mean of every three values of a list

查看:90
本文介绍了如何计算列表的每三个值的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

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

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

I want another list with mean of three values and so the new list be:

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

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

There will be only 6 values in the new list as there are only 18 elements in the first.

我正在寻找一种精巧的方法来完成此操作,而列表中的步骤最少.

I am looking for an elegant way to do this with a minimal number of steps for a large list.

推荐答案

您可以使用以3个间隔迭代的for循环获取first的一部分

You can take a slice of first using for loop that iterates in 3 interval

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]

这篇关于如何计算列表的每三个值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆