Jor*_*dan 3 python iterable operators python-3.x
sum(iterable) 有效地:
def sum(iterable):
s = 0
for x in iterable:
s = s.__add__(x)
return s
Run Code Online (Sandbox Code Playgroud)
Python是否有内置函数可以在不设置初始值的情况下完成此操作?
# add is interchangeable with sub, mul, etc.
def chain_add(iterable):
iterator = iter(iterable)
s = next(iterator)
while True:
try:
s = s.__add__(next(iterator))
except StopIteration:
return s
Run Code Online (Sandbox Code Playgroud)
我遇到的问题sum是它不适用于支持+运算符的其他类型,例如Counter.
尝试查看python reduce()函数:传入一个函数,一个可迭代的函数和一个可选的初始化函数,它会将函数累积地应用于所有值.
例如:
import functools
def f(x,y):
return x+y
print functools.reduce(f, [1, 2, 3, 4]) # prints 10
print functools.reduce(f, [1, 2, 3, 4], 10) # prints 20, because it initializes at 10, not 0.
Run Code Online (Sandbox Code Playgroud)
您可以根据您的iterable更改函数,因此它可以自定义.