循环地将操作数列表减少为单个结果



(这是另一个问题的重新讨论,自我回答的版本,由于没有被问好而已关闭。

我有一个整数列表:

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

我的目标是交替地对这些数字应用求和和法运算符以获得单个结果。

例如,对于此输入,结果为

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

减少到71。从本质上讲,这可以分解为:

t1 =  1 + 2 
t2 = t1 * 3 
t3 = t2 + 4
... 

等等。

奖励:欢迎可以推广到两个以上周期性操作的解决方案。

这是一个略有不同的答案,避免在 lambda 函数中使用next

import operator
from itertools import cycle
def apply_cyclic(numbers, functions):
numbers = iter(numbers)
functions = cycle(functions)
result = next(numbers)
for num, fun in zip(numbers, functions):
result = fun(result, num)
result num
print(apply_cyclic([1,2,3,4,5,6], [operator.add, operator.mul]))

这是针对这种情况的非迭代工具方法。

首先想象一下,有一个版本的functools.reduce一次从可迭代对象中获取 3 个项目。我们称这个假设函数为reduce3

如果存在,我们可以执行以下操作:

reduce3(lambda a, b, c: (a+b)*c, numbers)

如果我们要查看此操作的中间结果,我们将得到如下内容:

1, 2, 3, 4, 5, 6  # Initial list
9, 4, 5, 6        # Step 1
65, 6             # Step 2
(65 + 6) * ??     # Step 3

所以这几乎是我们想要的,除了在步骤 3 中没有第 3 项可以乘以。事实上,对于任何偶数长度列表都会发生这种情况。那么,如果长度为偶数,那么让我们将1附加到列表中:

if not len(numbers) % 2:
numbers.append(1)

在此之后,第三步将是:

(65 + 6)*1

这导致正确答案为 71。

不幸的是,这个神奇的功能并不存在。但是,我们可以修改原始列表以模仿此功能。我们只需要获取数字列表并将连续的数字对(不包括第一个元素(分组到元组中。此外,如果列表长度为偶数,我们需要将元素1添加到末尾。

本质上,让我们编写一个函数preprocess()[1, 2, 3, 4, 5, 6]转换为[1, (2, 3), (4, 5), (6, 1)]

def preprocess(myList):
my_output = [myList[0], *zip(numbers[1::2], numbers[2::2])]
if not len(myList) % 2:
my_output.append((myList[-1], 1))
return my_output
print(preprocess(numbers))
#[1, (2, 3), (4, 5), (6, 1)]

现在我们可以reduce处理后的列表:

from functools import reduce
result = reduce(lambda a, b: (a+b[0])*b[1], preprocess(numbers))
print(result)
#71

reducer需要 2 个输入 - 一个数字和一个元组。它将数字添加到元组的第一个元素,并将结果乘以第二个元素。结果是另一个数字,然后传递给下一个归约操作。


更新

这是reduceN的一般实现。N由传入函数的长度决定,因此可以推广到任意数量的函数。

from itertools import islice  # couldn't get away from itertools this time
def reduceN(functions, iterable, initializer=None):
it = iter(iterable)
n = len(functions)
if initializer is None:
value = next(it)
else:
value = initializer
elements = list(islice(it, n))
while(elements):
for fn, el in zip(functions, elements):
value = fn(value, el)
elements = list(islice(it, n))
return value

我们可以使用它来循环应用任意数量的函数。所以原始示例:

from operator import add, mul
numbers = [1, 2, 3, 4, 5, 6]
functions = [add, mul]
print(reduceN(functions, numbers))
#71

如果我们从numbers中删除最后一个元素:

print(reduceN(functions=functions, iterable=[1, 2, 3, 4, 5]))
#65

一种解决方案涉及使用itertools.cycle构建循环生成器并在functools.reduce中交替应用每个函数。

from itertools import cycle
from functools import reduce
import operator
fn = cycle((operator.add, operator.mul))
result = reduce(lambda x, y: next(fn)(x, y), numbers)

print(result)
71

此解决方案的优点是,您可以更改fn的定义,以便连续应用任意数量的运算符:

fn = cycle((operator.add, operator.mul, operator.sub, ...))

此外,当您一次只处理两个操作数时,不存在优先级问题。

注意:不支持一元运算符。

最新更新