使用Numpy或Scipy的累积产品

编程入门 行业动态 更新时间:2024-10-28 17:24:08
本文介绍了使用Numpy或Scipy的累积产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个一维numpy数组,希望将其转换为其累积积.天真的实现是这样的:

I have a 1-D numpy array that I wish to convert it to its cumulative product. A naive implementation would be this:

import numpy as np arr = [1,2,3,4,5,6,7,8,9,10] c_sum = [np.prod(arr[:i]) for i in range(1, len(arr) + 1)] # c_sum = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

但是,当 arr 的大小变得很大时,这可能会变慢.我怀疑使用 Numpy 或 Scipy 阵列魔术之一可能会有更有效的方法.有人可以告诉我该怎么做吗?

However this could get slow when the size of arr gets very large. I suspect that there might be a more efficient way using one of the Numpy or Scipy array magics. Can someone show me how to do it?

推荐答案

您可以使用 numpy.cumprod :

You can use numpy.cumprod:

>>> np.cumprod(arr) array([ 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800], dtype=int32)

以防万一您不想使用numpy并宁愿呆在纯python中(也许是因为您想要python不受限制的精度整数并且不太在乎速度),您也可以使用 itertools.accumulate :

>>> import itertools >>> import operator >>> list(itertools.accumulate(arr, operator.mul)) [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

注意: itertools.accumulate 函数需要python3.

Note: The itertools.accumulate function requires python3.

更多推荐

使用Numpy或Scipy的累积产品

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

发布评论

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

>www.elefans.com

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