使用 reduce 将 python 中的成对元素相乘

Multiplying paired elements in python using reduce

对于这样的列表:

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

我想使用下面的代码来乘以这样的成对元素:

(a[0] + a[1]) * (a[2] + a[3]) * (a[4] + a[5])

我试过使用类似的东西:

reduce((lambda x, y: (x+y)), numbers) 

和:

reduce((lambda x, y: (x+y)*(x+y)), numbers) 

但我不知道如何让它适用于整个列表。任何帮助将不胜感激。

整个解决方案必须适合 reduce,我不能导入任何其他模块。

你可以reduce你自己的生成器,它给出你的迭代中的对的总和:

def pairwise_sum(seq):
    odd_length = len(seq) % 2

    it = iter(seq)
    for item1, item2 in zip(it, it):
        yield item1 + item2
    if odd_length:
        yield seq[-1]

>>> reduce(lambda x, y: x*y, pairwise_sum([1,2,3,4,5,6]))
231

或者,如果您希望它更通用,您可以使用 grouper recipe 将所有对相加,然后使用 reduce 将所有总和相乘:

from itertools import zip_longest
from functools import reduce
from operator import mul

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

>>> reduce(mul, map(sum, grouper([1,2,3,4,5,6], 2, fillvalue=0)))
231

可以分两步完成:

  1. 对列表中的连续项目求和:[sum(a[i:i+2]) for i in range(0, len(a), 2)]
  2. 应用减少:reduce(lambda x, y: x * y, new_list)

将它们组合在一起:

reduce(lambda x, y: x * y, [sum(a[i:i+2]) for i in range(0, len(a), 2)])