代码之家  ›  专栏  ›  技术社区  ›  Abhishek

在python映射函数中使用reduce

  •  3
  • Abhishek  · 技术社区  · 8 年前

    在这种情况下,我有一个列表列表,需要对第一个列表的每个子列表应用reduce。 reduce函数需要两个参数,但第二个参数(我要应用reduce的列表)应该来自传递给map函数的主列表

    reducedLists = map(reduce(lambda first, second : map(operator.add, first,second), XXX), listsToReduce)
    

    我需要知道应该通过什么来代替 XXX 在上面

    在这里 listsToReduce [[[1,2,3], [3,2,1]],[[1,3,5],[5,3,1]]] .

    我想要上述地图的最终输出,并减少到2个列表 [[4,4,4],[6,6,6]] 我不知道如何对映射和reduce进行建模,以便将适当的参数传递给reduce函数。

    我的最终目标是使用 Pool.map multiprocessing 在多核上执行reduce操作的包。如果您在重构代码时考虑到这一点,我们将不胜感激。

    2 回复  |  直到 8 年前
        1
  •  2
  •   PM 2Ring    8 年前

    我将以这种方式执行成对求和操作:

    listsToReduce = [[[1,2,3], [3,2,1]], [[1,3,5], [5,3,1]]]
    reducedLists = [list(map(sum, zip(*lst))) for lst in listsToReduce]
    print(reducedLists)
    

    输出

    [[4, 4, 4], [6, 6, 6]]
    

    map

    [map(sum, zip(*lst)) for lst in listsToReduce]
    

    但我强烈建议在所有新代码中使用Python 3,因为Python 2将在2020年正式停止使用。


    在Python 2中还有另一种方法,但由于使用了 lambda 函数而不是 sum

    from operator import add
    
    reducedLists = map(lambda t: map(add, *t), listsToReduce)
    
        2
  •  0
  •   user211337    5 年前

    from functools import partial, reduce
    import operator
    
    listsToReduce = [[[1,2,3], [3,2,1]],[[1,3,5],[5,3,1]]]
    
    f = partial(reduce, lambda first, second : list(map(operator.add, first,second)))
    map(f, listsToReduce)