sum(iterable)
有效地:
def sum(iterable):
s = 0
for x in iterable:
s = s.__add__(x)
return s
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
我遇到的问题sum
是它不适用于支持+
运算符的其他类型,例如Counter
.