<分区>
Possible Duplicate:
Returning the product of a list
除了这种方式,还有其他方法可以获取列表的产品吗:
def prod(L):
p=1
for i in L:
p= i * p
return p
这段代码是正确的,但我需要找到另一种方法来做到这一点。我真的找不到它。
<分区>
Possible Duplicate:
Returning the product of a list
除了这种方式,还有其他方法可以获取列表的产品吗:
def prod(L):
p=1
for i in L:
p= i * p
return p
这段代码是正确的,但我需要找到另一种方法来做到这一点。我真的找不到它。
最佳答案
使用 reduce(f, iterable[, initializer])
:
>>> from operator import mul
>>> reduce(mul, [1, 2, 3], 1)
6
reduce()
抽象出以下模式:
a ⊗ b ⊗ c ⊗ d ⊗ e ...
其中 ⊗
是二元(左结合)运算符,即接受两个参数的函数。
关于python - 列表python的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807722/