List comprehension vs map

前端 未结 11 1807
长情又很酷
长情又很酷 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:02

    Actually, map and list comprehensions behave quite differently in the Python 3 language. Take a look at the following Python 3 program:

    def square(x):
        return x*x
    squares = map(square, [1, 2, 3])
    print(list(squares))
    print(list(squares))
    

    You might expect it to print the line "[1, 4, 9]" twice, but instead it prints "[1, 4, 9]" followed by "[]". The first time you look at squares it seems to behave as a sequence of three elements, but the second time as an empty one.

    In the Python 2 language map returns a plain old list, just like list comprehensions do in both languages. The crux is that the return value of map in Python 3 (and imap in Python 2) is not a list - it's an iterator!

    The elements are consumed when you iterate over an iterator unlike when you iterate over a list. This is why squares looks empty in the last print(list(squares)) line.

    To summarize:

    • When dealing with iterators you have to remember that they are stateful and that they mutate as you traverse them.
    • Lists are more predictable since they only change when you explicitly mutate them; they are containers.
    • And a bonus: numbers, strings, and tuples are even more predictable since they cannot change at all; they are values.

提交回复
热议问题