Python-平均每个"n"个列表中的元素 [英] Python - Average every "n" elements in a list

查看:61
本文介绍了Python-平均每个"n"个列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要平均Python列表中的每个 n 个元素,在此示例中, n = 3 :

I need to average every n elements in Python list, n = 3 in this example:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

这样输出列表将是:

list2 = [2, 2, 2, 5, 5, 5, 8, 8, 8]

推荐答案

您可以像这样在列表理解中计算 [2,5,8] 列表:

You can compute the [2,5,8] list in a list comprehension like this:

list1 = [1,2,3,4,5,6,7,8,9]
n = 3

list2 = [sum(list1[i:i+n])//n for i in range(0,len(list1),n)]

然后按照您的要求将其放回 list1 (保留大小):

Then put it back in list1 (preserving size) like you requested like this:

for i in range(0,len(list1)):
    list1[i] = list2[i//n]

或具有列表理解:

list1 = [list2[i//n] for i in range(len(list1))]

最终找到了一个很好的oneliner来总结:

Final edit: found a nice oneliner to sum it all up:

import itertools
list1 = list(itertools.chain.from_iterable([i]*n for i in [sum(list1[i:i+n])//n for i in range(0,len(list1),n)]))

这篇关于Python-平均每个"n"个列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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