How to use filter, map, and reduce in Python 3

前端 未结 7 1705
夕颜
夕颜 2020-11-22 08:27

filter, map, and reduce work perfectly in Python 2. Here is an example:

>>> def f(x):
        return x % 2 !=         


        
7条回答
  •  遇见更好的自我
    2020-11-22 09:16

    The functionality of map and filter was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in functools.reduce.

    So, for filter and map, you can wrap them with list() to see the results like you did before.

    >>> def f(x): return x % 2 != 0 and x % 3 != 0
    ...
    >>> list(filter(f, range(2, 25)))
    [5, 7, 11, 13, 17, 19, 23]
    >>> def cube(x): return x*x*x
    ...
    >>> list(map(cube, range(1, 11)))
    [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
    >>> import functools
    >>> def add(x,y): return x+y
    ...
    >>> functools.reduce(add, range(1, 11))
    55
    >>>
    

    The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions. Example:

    >>> def f(x): return x % 2 != 0 and x % 3 != 0
    ...
    >>> [i for i in range(2, 25) if f(i)]
    [5, 7, 11, 13, 17, 19, 23]
    >>> def cube(x): return x*x*x
    ...
    >>> [cube(i) for i in range(1, 11)]
    [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
    >>>
    

    They say that for loops are 99 percent of the time easier to read than reduce, but I'd just stick with functools.reduce.

    Edit: The 99 percent figure is pulled directly from the What’s New In Python 3.0 page authored by Guido van Rossum.

提交回复
热议问题