2017-04-19 34 views
0

我有以下列表:在列表中相乘连续的数字?

list1 = [1, 5, 7, 13, 29, 35, 65, 91, 145, 203, 377, 455, 1015, 1885, 2639, 13195] 

如何繁衍列表中的每个号码?例如1 * 5 * 7 * 13 * 29..etc

上午我正确的轨道下方?:

for numbs in list1: 
    numbs * list1[#iterate through list1, starting on 2nd item in list1] 

回答

8

这里最简单的方法的代码上是使用一个reduce操作这正是这一点:

from functools import reduce 
import operator 

reduce(operator.mul, [1, 2, 3]) 
>>> 6 

减少基本上是说:将此操作应用于索引0和1.获取结果,然后将操作应用于该结果和索引2.因此,等等。

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

def multiply(a, b): 
    return a * b 
reduce(multiply, [1,2,3]) 

这将完全相同的事情。

reduce函数可以在Python 2中使用,但是可以使用it was removed and is only available in functools in Python 3。确保导入reduce将确保Python 2/3兼容性。

3

作为替代品operator模块和operator.mul,你可以这样做:

  • 一个基本的for循环:

    list1 = [1,2,3,4,5] 
    product = 1 
    for item in list1: 
        product *= item 
    print(product)   # 120 
    
  • 使用numpy模块:

    from numpy import prod 
    list1 = [1,2,3,4,5] 
    print(prod(list1))  # 120 
    
  • 导入functools a第二应用λ-功能:

    from functools import reduce 
    list1 = [1,2,3,4,5] 
    print(reduce(lambda x, y: x * y, list1))  # 120 
    

    from functools import reduce 
    list1 = [1,2,3,4,5] 
    prodFunc = lambda x, y: x * y 
    print(reduce(prodFunc, list1))  # 120 
    

    ,而不拉姆达:

    from functools import reduce 
    list1 = [1,2,3,4,5] 
    def prodFunc(a,b): 
        return a * b 
    print(reduce(prodFunc, list1))  # 120