在Python 3中,reduce()已经移动到functools.reduce()并且显然最好使用列表推导或普通循环以获得更好的可读性.
我想打印列表中所有元素的XOR'ed值.
# My implementation with functools
from functools import reduce
print(reduce(lambda a, b: a^b, [1, 3, 2, 3, 4, 4, 5, 2, 1]))
Run Code Online (Sandbox Code Playgroud)
我有这个:
# My implementation without functools
def XOR(x):
ans = 0
for i in x:
ans = ans ^ i
return ans
print(XOR([1, 3, 2, 3, 4, 4, 5, 2, 1]))
Run Code Online (Sandbox Code Playgroud)
如何在不编写更多功能版本的代码reduce()?
(请提供Python 3中的参考或代码,如果有的话.)
Mar*_*ers 10
虽然Guido van Rossum没有太在意reduce(),但社区中有足够的人想要它,这就是为什么它被移动到functools并且没有彻底删除的原因.它具有高性能,非常适合您的使用案例.只是使用它.
通过使用operator.xor()以避免lambda的新Python框架的开销,可以使您的案例更快,更可读:
from functools import reduce
from operator import xor
reduce(xor, [1, 3, 2, 3, 4, 4, 5, 2, 1])
Run Code Online (Sandbox Code Playgroud)
双方xor()并reduce()在C.实现回叫Python解释器循环的lambda比较调用另一个C函数是相当缓慢.
如果你真的必须使用一个函数,那么使用
def xor_reduce(values):
result = 0
for value in values:
result ^= value
return result
Run Code Online (Sandbox Code Playgroud)
使用就地XOR和更好的变量名称.
| 归档时间: |
|
| 查看次数: |
206 次 |
| 最近记录: |