Difference between map and list iterators in python3

前端 未结 1 1451
时光取名叫无心
时光取名叫无心 2021-01-26 04:48

I ran into unexpected behaviour when working with map and list iterators in python3. In this MWE I first generate a map of maps. Then, I want the first element of each map in on

1条回答
  •  猫巷女王i
    2021-01-26 05:23

    A map() is an iterator; you can only iterate over it once. You could get individual elements with next() for example, but once you run out of items you cannot get any more values.

    I've given your objects a few easier-to-remember names:

    >>> s = [[1, 2, 3], [4, 5, 6]]
    >>> map_of_maps = map(lambda l: map(lambda t: t, l), s)
    >>> first_elements = map(next, map_of_maps)
    

    Iterating over first_elements here will in turn iterate over map_of_maps. You can only do so once, so once we run out of elements any further iteration will fail:

    >>> next(first_elements)
    1
    >>> next(first_elements)
    4
    >>> next(first_elements)
    Traceback (most recent call last):
      File "", line 1, in 
    StopIteration
    

    list() does exactly the same thing; it takes an iterable argument, and will iterate over that object to create a new list object from the results. But if you give it a map() that is already exhausted, there is nothing to copy into the new list anymore. As such, you get an empty result:

    >>> list(first_elements)
    []
    

    You need to recreate the map() from scratch:

    >>> map_of_maps = map(lambda l: map(lambda t: t, l), s)
    >>> first_elements = map(next, map_of_maps)
    >>> list(first_elements)
    [1, 4]
    >>> list(first_elements)
    []
    

    Note that a second list() call on the map() object resulted in an empty list object, once again.

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