Python:使用reduce来交替添加和乘法

时间:2017-10-12 23:17:58

标签: python reduce

仅使用reduce(因此不导入任何内容),如何编写单行函数以获得以下结果?它在列表中添加和乘以元素之间交替。

所有东西都需要适合reduce()

numbers = [1, 2, 3, 4, 5, 6]

((1 + 2) * 3 + 4) * 5 + 6 = 71

2 个答案:

答案 0 :(得分:3)

我猜你想要这样的东西:

print(reduce(lambda a, b: a[1] + b[1] if isinstance(a,tuple) 
           else a + b[1] if b[0] % 2 else a * b[1], enumerate(numbers)))

故障:

print( reduce(lambda a, b: a[1] + b[1] if isinstance(a, tuple) 
                           else a + b[1] if b[0] % 2 
                           else a * b[1], 
              enumerate(numbers)
             )
)

答案 1 :(得分:3)

您可以使用以下内容获得更清洁的解决方案:

def myCycle(x, y):
    while True:
        yield from (x, y)  # replace with yield x; yield y for python < 3.3

print (reduce(lambda x, y: (y[0], x[0](x[1], y[1])), 
                  zip(myCycle(int.__add__, int.__mul__), numbers))[-1])
71

myCycle这里是itertools.cycle的替身,它会反复循环播放元素。