resolving map function issue in python 3 vs python 2

后端 未结 2 605
轻奢々
轻奢々 2020-12-21 10:54

I\'m interested in functional programming with python and am working through Mary Rose Cook\'s blog post A practical introduction to functional programming.

相关标签:
2条回答
  • 2020-12-21 11:11

    To supplement @dhke's excellent answer (this is too long for a comment) think of it this way. You want to perform multiple transformations on a list by combining map, filter, etc. So there are two ways to think of this:

    1. Apply the first transformation to the entire list, then the second, etc.
    2. Apply all the transformations to the first element of the list, then the second, etc.

    The python3 way allows for either, whereas the second cannot be written as succinctly in python 2: you would have to explicitly iterate the list with a for loop and build up a new list of the results.

    0 讨论(0)
  • 2020-12-21 11:28

    As documented, in the migration guide,

    In Python 2 map() returns a list while in Python 3 it returns an iterator.

    Python 2:

    Apply function to every item of iterable and return a list of the results.

    Python 3:

    Return an iterator that applies function to every item of iterable, yielding the results.

    Python 2 always does the equivalent of list(imap(...)), Python 3 allows for lazy evaluation.

    0 讨论(0)
提交回复
热议问题