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

前端 未结 7 1707
夕颜
夕颜 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条回答
  •  旧时难觅i
    2020-11-22 08:56

    You can read about the changes in What's New In Python 3.0. You should read it thoroughly when you move from 2.x to 3.x since a lot has been changed.

    The whole answer here are quotes from the documentation.

    Views And Iterators Instead Of Lists

    Some well-known APIs no longer return lists:

    • [...]
    • map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).
    • [...]

    Builtins

    • [...]
    • Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.
    • [...]

提交回复
热议问题