将列表中的连续数字相乘?

And*_*pes 0 python loops

我有以下列表:

list1 = [1, 5, 7, 13, 29, 35, 65, 91, 145, 203, 377, 455, 1015, 1885, 2639, 13195]
Run Code Online (Sandbox Code Playgroud)

如何将列表中的每个数字相乘?例如1 * 5 * 7 * 13 * 29..etc.

我是否正确使用下面的代码?:

for numbs in list1:
    numbs * list1[#iterate through list1, starting on 2nd item in list1] 
Run Code Online (Sandbox Code Playgroud)

Sla*_*off 8

这里最简单的方法是使用一个reduce完全按此操作的操作:

from functools import reduce
import operator

reduce(operator.mul, [1, 2, 3])
>>> 6
Run Code Online (Sandbox Code Playgroud)

Reduce基本上是这样说:将此操作应用于索引0和1.获取结果,然后将操作应用于该结果和索引2.依此类推.

operator.mul 只是用于表示乘法的少量语法糖,它可以很容易地被另一个函数替换.

def multiply(a, b):
    return a * b
reduce(multiply, [1,2,3])
Run Code Online (Sandbox Code Playgroud)

这将做同样的事情.

reduce函数在Python 2中作为内置函数提供,但它已被删除,仅在Python 3中的functools中可用.确保导入reduce将确保Python 2/3兼容性.


Mr.*_*der 5

作为operator模块 和 的替代方案operator.mul,您可以这样做: