2017-04-19 32 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