列表的累积乘积 [英] Cumulative product of a list

查看:107
本文介绍了列表的累积乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了所有定数的所有素数的列表. 我试图做的事情很难解释,所以我只用一些硬代码来展示它:

I have implemented a list of all prime numbers from a set amount. What I'm trying to do is hard to explain so I'll just show it with some hard code:

euclst = []
euclst.append((primelst[0]) + 1)
euclst.append((primelst[0] * primelst[1]) + 1)
euclst.append((primelst[0] * primelst[1] * primelst[2]) + 1)
....

所以从本质上讲,我试图从上一个列表中按顺序提取单个元素,然后将其按指数倍增,然后将其附加到其他列表中.

So essentially I'm trying to take a single element in order from my prev list and multiplying it exponentially I guess and appending it to my other list.

我意识到我可以做到这一点,这可能会更容易:

I realized that I could just do this, which is probably easier:

euclst = []
euclst.append(primelst[0])
euclst.append(primelst[0] * primelst[1])
euclst.append(primelst[0] * primelst[1] * primelst[2])
....
#then add one to each element in the list later

我需要一些想法才能在某种循环中做到这一点.

I need some ideas to do this in a loop of some sort.

推荐答案

您需要累积产品的列表.这是一个简单的食谱:

You want a list of the cumulative product. Here's a simple recipe:

>>> primelist =  [2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> euclist = []
>>> current = 1
>>> for p in primelist:
...     current *= p
...     euclist.append(current)
...
>>> euclist
[2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870]
>>>

使用itertools的另一种方法:

Another way, using itertools:

>>> import itertools
>>> import operator
>>> list(itertools.accumulate(primelist, operator.mul))
[2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870]
>>>

或者,也许这就是您的意思:

OR, perhaps this is what you mean:

>>> [x + 1 for x in itertools.accumulate(primelist, operator.mul)]
[3, 7, 31, 211, 2311, 30031, 510511, 9699691, 223092871]

具有等效的for循环:

With the equivalent for-loop:

>>> euclist = []
>>> current = 1
>>> for p in primelist:
...     current = current*p
...     euclist.append(current + 1)
...
>>> euclist
[3, 7, 31, 211, 2311, 30031, 510511, 9699691, 223092871]
>>>

这篇关于列表的累积乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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