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

问题描述 投票:2回答:2

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

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

如果我想用orandxor等不同的运算符总结一个列表怎么办?

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

python algorithm data-structures sum
2个回答
5
投票

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

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

import functools

functools.reduce(lambda a, b: a ^ b, [1, 2, 3])

这相当于1 ^ 2 ^ 3


4
投票

functools.reduce的替代方法是编写一个明确的for循环:

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

xor_reduce([1, 2, 3])

如果你想采用reduce方式(对于IMO来说不是那么不合理),我会使用operator模块:

from functools import reduce
from operator import xor

reduce(xor, [1, 2, 3])

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

from operator import or_, and_
reduce(or_, [1, 2, 3])
reduce(and_, [1, 2, 3])

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

any([1, 2, 3])
all([1, 2, 3])
© www.soinside.com 2019 - 2024. All rights reserved.