【问题标题】:Multiplying paired elements in python using reduce使用reduce在python中乘以成对元素
【发布时间】:2018-03-24 23:06:42
【问题描述】:

对于类似的列表:

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,我不能导入任何其他模块。

【问题讨论】:

  • 您需要成对迭代,将数字相加然后减少结果的乘法。

标签: python list reduce itertools


【解决方案1】:

分两步完成:

  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)])

【讨论】:

  • 我来这里是为了说这个,除了我使用int.__mul__而不是lambda,假设列表中的项目总是整数。
  • 使用sum(a[i:i+2]) 可能更好,否则这不适用于奇数长度的列表(当前会引发 IndexError)。否则很好的解决方案!
【解决方案2】:

你可以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

【讨论】:

  • 不幸的是,我唯一可以使用的导入是 reduce。
  • 你可以在问题中这么说。
  • @T.J.没问题,我更新了答案,包括不依赖进口的版本。
  • 超级聪明的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 2014-02-27
  • 2017-06-20
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2018-10-23
相关资源
最近更新 更多