mou*_*nho 2 python algorithm sum data-structures
在python中,我们可以将列表总结为:sum(list_of_integers).
现在sum只是运算符中两个元素之间的操作+.
如果我想要什么总结与不同的运营商像一个列表or,and,xor等?
我可以使用for循环逐个手动完成,但必须有更好的方法.
functools.reduce非常适合这种用例.它需要一个函数来应用累计值和下一个值,您想要减少的可迭代值,以及可选的初始值.
例如,按位或按列表中的每个值:
import functools
functools.reduce(lambda a, b: a ^ b, [1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
这相当于1 ^ 2 ^ 3.
另一种方法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模块(在标准库中,因此应始终可用)还将所有其他标准操作定义为函数,但添加了foror和and尾随_,因为它们是保留关键字:
from operator import or_, and_
reduce(or_, [1, 2, 3])
reduce(and_, [1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
虽然对于这两个你可以使用内置函数any和all:
any([1, 2, 3])
all([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)