在Python中对具有不同运算符的列表求和

mou*_*nho 2 python algorithm sum data-structures

在python中,我们可以将列表总结为:sum(list_of_integers).

现在sum只是运算符中两个元素之间的操作+.

如果我想要什么总结与不同的运营商像一个列表or,and,xor等?

我可以使用for循环逐个手动完成,但必须有更好的方法.

Chr*_*ott 5

functools.reduce非常适合这种用例.它需要一个函数来应用累计值和下一个值,您想要减少的可迭代值,以及可选的初始值.

例如,按位或按列表中的每个值:

import functools

functools.reduce(lambda a, b: a ^ b, [1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

这相当于1 ^ 2 ^ 3.

  • @mourinho`reduce`*使用*成为Python 2中`builtins`模块的一部分,但它被降级为`functools`,因为,[Guido只是不喜欢它](https://stackoverflow.com /问题/ 181543 /什么,是最问题与 - 减少).不想使用核心库似乎是一种人为限制.否则,请注意,Guido建议使用for循环.如果你不想要"减少",这似乎是最直接的方式 (5认同)
  • 不使用标准库似乎是一个非常随意的限制.这是作业吗? (3认同)

Gra*_*her 5

另一种方法functools.reduce是编写一个显式for循环:

def xor_reduce(args):
    result = 0
    for x in args:
        result ^= x
    return result

xor_reduce([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

如果您愿意reduce(IMO),我会使用该operator模块:

from functools import reduce
from operator import xor

reduce(xor, [1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

operator模块(在标准库中,因此应始终可用)还将所有其他标准操作定义为函数,但添加了fororand尾随_,因为它们是保留关键字:

from operator import or_, and_
reduce(or_, [1, 2, 3])
reduce(and_, [1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

虽然对于这两个你可以使用内置函数anyall

any([1, 2, 3])
all([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)