Tarik
Tarik

Reputation: 11209

Built in aggregate function in python

Is there a built-in aggregate function in Python? Example code:

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)

Output:

45
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Upvotes: 2

Views: 962

Answers (1)

unutbu
unutbu

Reputation: 879739

You could use 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]

Upvotes: 2

Related Questions