When would you use reduce() instead of sum()?

后端 未结 4 1897
温柔的废话
温柔的废话 2021-01-02 00:52

I began learning functional programming recently, and came up with this example when attempting to calculate my quiz average for a class.

The example I came up with

4条回答
  •  长发绾君心
    2021-01-02 01:06

    reduce and sum do very different things. Consider a question like "I have a nested dictionary ...

    d = {'foo': {'bar': {'baz': 'qux'}}}
    

    and I would like to get the value associated with a list of keys: ['foo', 'bar', 'baz']". This could call for a reduce (if you're a functional programming kind of person):

    >>> reduce(lambda subdict, k: subdict[k], ['foo', 'bar', 'baz'], d)
    'qux'
    

    Note, you can't do this with sum. It just happens that summing is an easy example to show what is happening with reduce (since you can write it out with parenthesis and most programmers are familiar with how parenthesis group mathematical operations).

提交回复
热议问题