Python:使用reduce交替加法和乘法
Python: Use reduce to alternate addition and multiplication
仅使用 reduce(因此不导入任何内容),如何编写一个单行函数来获得以下结果?它在列表中交替添加和乘以元素。
一切都需要适应 reduce()
numbers = [1, 2, 3, 4, 5, 6]
((1 + 2) * 3 + 4) * 5 + 6 = 71
我猜你想要这样的东西:
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)
)
)
您可以使用如下方式获得更清洁的解决方案:
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
的替代品,它反复循环元素。
仅使用 reduce(因此不导入任何内容),如何编写一个单行函数来获得以下结果?它在列表中交替添加和乘以元素。
一切都需要适应 reduce()
numbers = [1, 2, 3, 4, 5, 6]
((1 + 2) * 3 + 4) * 5 + 6 = 71
我猜你想要这样的东西:
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)
)
)
您可以使用如下方式获得更清洁的解决方案:
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
的替代品,它反复循环元素。