[英]Product of a list
I am using the following code to find the list of primes, but I also need to be able to find the product of the list created. 我正在使用以下代码查找素数列表,但我还需要能够找到所创建列表的乘积。 I don't know where to start. 我不知道从哪里开始。
def list_of_primes(x):
primes = [2, 3]
n = primes[-1] + 2
while len(primes) < x:
for p in primes:
if n % p == 0:
break
else:
primes.append(n)
n += 2
return (primes)
You can either maintain a variable that stores the running product or do something like 您可以维护存储正在运行的产品的变量,也可以执行类似的操作
reduce(operator.mul, primes) # product of elements in `primes`
(using reduce
with operator.mul
) (与operator.mul
一起使用reduce
)
Performance-wise, you shouldn't see a large gap between these two approaches for any reasonably sized list; 从性能角度看,对于任何大小合理的列表,这两种方法之间都不会出现很大的差距; you should use whichever makes more sense in the context of your program. 您应该使用在程序上下文中更有意义的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.