2017-04-19 1 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.

from functools import reduce 
import operator 

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

기본적으로 말하고있는 줄 :?

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

답변

8

여기에 가장 쉬운 방법 아래의 코드를 사용하여 올바른 궤도에

오전 나는 정확히이 일을 수행하는 reduce 작업을 사용하는 것 :이 작업을 인덱스 0과 1에 적용합니다. 결과를 가져 와서 해당 결과와 인덱스 2에 연산을 적용합니다.

operator.mul은 곱셈을 표현하기위한 구문 당 (syntactic sugar)에 불과하며 다른 기능으로 쉽게 대체 될 수 있습니다.

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

정확히 똑같은 작업을 수행합니다.

reduce 함수는 파이썬 2에 내장되어 있지만 it was removed and is only available in functools in Python 3에서 사용할 수 있습니다. reduce를 가져 오기 위해서는 Python 2/3 호환성을 보장해야합니다.

3

대안 operator 모듈과 operator.mul, 당신은이 작업을 수행 할 수 있습니다

  • 을 기본-루프 :

    from numpy import prod 
    list1 = [1,2,3,4,5] 
    print(prod(list1))  # 120 
    
  • :

    list1 = [1,2,3,4,5] 
    product = 1 
    for item in list1: 
        product *= item 
    print(product)   # 120 
    
  • numpy 모듈을 사용

    functools a를 가져오고 있습니다. ND 람다 함수를 적용

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

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 

또는,

관련 문제