List comprehension vs map

前端 未结 11 1805
长情又很酷
长情又很酷 2020-11-21 04:39

Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic

11条回答
  •  攒了一身酷
    2020-11-21 05:15

    Python 2: You should use map and filter instead of list comprehensions.

    An objective reason why you should prefer them even though they're not "Pythonic" is this:
    They require functions/lambdas as arguments, which introduce a new scope.

    I've gotten bitten by this more than once:

    for x, y in somePoints:
        # (several lines of code here)
        squared = [x ** 2 for x in numbers]
        # Oops, x was silently overwritten!
    

    but if instead I had said:

    for x, y in somePoints:
        # (several lines of code here)
        squared = map(lambda x: x ** 2, numbers)
    

    then everything would've been fine.

    You could say I was being silly for using the same variable name in the same scope.

    I wasn't. The code was fine originally -- the two xs weren't in the same scope.
    It was only after I moved the inner block to a different section of the code that the problem came up (read: problem during maintenance, not development), and I didn't expect it.

    Yes, if you never make this mistake then list comprehensions are more elegant.
    But from personal experience (and from seeing others make the same mistake) I've seen it happen enough times that I think it's not worth the pain you have to go through when these bugs creep into your code.

    Conclusion:

    Use map and filter. They prevent subtle hard-to-diagnose scope-related bugs.

    Side note:

    Don't forget to consider using imap and ifilter (in itertools) if they are appropriate for your situation!

提交回复
热议问题