使用 reduce

def multiply(s1, s2):
    print('{arg1} * {arg2} = {res}'.format(arg1=s1, 
                                           arg2=s2, 
                                           res=s1*s2))
    return s1 * s2

asequence = [1, 2, 3]

給定 initializer,通過將函式應用於初始化器和第一個可迭代元素來啟動該函式:

cumprod = reduce(multiply, asequence, 5)
# Out: 5 * 1 = 5
#      5 * 2 = 10
#      10 * 3 = 30
print(cumprod)
# Out: 30

沒有 initializer 引數,reduce 首先將函式應用於前兩個列表元素:

cumprod = reduce(multiply, asequence)
# Out: 1 * 2 = 2
#      2 * 3 = 6
print(cumprod)
# Out: 6