仅使用reduce(因此不导入任何内容),如何编写单行函数以获得以下结果?它在列表中添加和乘以元素之间交替。
所有东西都需要适合reduce()
numbers = [1, 2, 3, 4, 5, 6]
((1 + 2) * 3 + 4) * 5 + 6 = 71
答案 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
的替身,它会反复循环播放元素。