Python中是否有内置的聚合函数? 示例代码:
def aggregate(iterable, f, *args):
if len(args) == 1:
accumulator = args[0]
elif len(args) == 0:
accumulator = None
else:
raise Exception("Invalid accumulator")
for i, item in enumerate(iterable):
if i == 0 and accumulator == None:
accumulator = item
else:
accumulator = f(accumulator, item)
return accumulator
if __name__ == "__main__":
l = range(10)
s1 = aggregate(l, lambda s, x : s+x)
print(s1)
s2 = aggregate(l, lambda s, x : "{}, {}".format(s, x))
print(s2)
s3 = aggregate(l, lambda s, x: [x] + s, list())
print(s3)
输出:
45
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
答案 0 :(得分:2)
您可以使用functools.reduce
:
import functools
functools.reduce(lambda s, x: s+x, range(10)))
# 45
functools.reduce(lambda s, x: "{}, {}".format(s, x), range(10))
# '0, 1, 2, 3, 4, 5, 6, 7, 8, 9'
functools.reduce(lambda s, x: [x] + s, range(10), [])
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]