NumPy数组中连续值的总和

编程入门 行业动态 更新时间:2024-10-28 20:30:08
本文介绍了NumPy数组中连续值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个包含10个值的numpy数组a.此处只是一个示例情况,尽管我想对长度为100的数组重复相同的操作.

Let's say I have a numpy array a containing 10 values. Just an example situation here, although I would like to repeat the same for an array with length 100.

a = np.array([1,2,3,4,5,6,7,8,9,10])

我想对前5个值求和,然后对后5个值求和,依此类推,然后将它们存储在一个新的空白列表中,例如b.

I would like to sum the first 5 values followed by the second 5 values and so on and store them in a new empty list say b.

所以b将包含b = [15,40].

我该怎么做?

推荐答案

尝试使用此列表理解:

b = [sum(a[current: current+5]) for current in xrange(0, len(a), 5)]

从列表中一次获取5个切片,将它们相加并构造一个列表.也适用于长度不是5的倍数的列表.

It takes slices of 5 at a time from the list, sums them up and constructs a list. Also works for lists which aren't a multiple of 5 in length.

(xrange在python3 +中应为range)

(xrange should be range in python3+)

更多推荐

NumPy数组中连续值的总和

本文发布于:2023-11-22 18:09:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   组中   NumPy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!