Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的内置聚合函数_Python_Aggregate - Fatal编程技术网

python中的内置聚合函数

python中的内置聚合函数,python,aggregate,Python,Aggregate,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 enumerat

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]
您可以使用:


functools.reduce
通过编写
def aggregate(iterable,f,acculator=None),可以大大简化函数的开头部分:
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]