How does reduce function work?

前端 未结 9 1154
青春惊慌失措
青春惊慌失措 2020-12-01 04:25

As far as I understand, the reduce function takes a list l and a function f. Then, it calls the function f on first two elements of th

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 04:47

    Beyond the trivial examples, here is one where I find reduce to be actually quite useful:

    Imagine an iterable of ordered int values, often with some runs of contiguous values, and that we'd like to "summarize" it as a list of tuples representing ranges. (Note also that this iterable could be a generator of a very long sequence --another reason to use reduce and not some operation on an in-memory collection).

    from functools import reduce
    
    def rle(a, b):
        if a and a[-1][1] == b:
            return a[:-1] + [(a[-1][0], b + 1)]
        return a + [(b, b + 1)]
    
    reduce(rle, [0, 1, 2, 5, 8, 9], [])
    # [(0, 3), (5, 6), (8, 10)]
    

    Notice the use of a proper initial value ([] here) for reduce.

    Corner cases handled as well:

    reduce(rle, [], [])
    # []
    
    reduce(rle, [0], [])
    # [(0, 1)]
    

提交回复
热议问题