Python: casting map object to list makes map object empty?

前端 未结 3 1940
轮回少年
轮回少年 2020-11-28 15:36

I have a map object that I want to print as a list but continue using as a map object afterwards. Actually I want to print the length so I cast to list but the issue also ha

相关标签:
3条回答
  • 2020-11-28 15:47

    The reason is that the Python 3 map returns an iterator and listing the elements of an iterator "consumes" it and there's no way to "reset" it

    my_map = map(str,range(5))
    
    list(my_map)
    # Out: ['0', '1', '2', '3', '4']
    
    list(my_map)
    # Out: []
    

    If you want to preserve the map object you can use itertools.tee to create a copy of the iterator to be used later

    from itertools import tee
    
    my_map, my_map_iter = tee(map(str,range(5)))
    
    list(my_map)
    # Out: ['0', '1', '2', '3', '4']
    
    list(my_map)
    # Out: []
    
    list(my_map_iter)
    # Out: ['0', '1', '2', '3', '4']
    
    0 讨论(0)
  • 2020-11-28 15:49

    A map object is a generator returned from calling the map() built-in function. It is intended to be iterated over (e.g. by passing it to list()) only once, after which it is consumed. Trying to iterate over it a second time will result in an empty sequence.

    If you want to save the mapped values to reuse, you'll need to convert the map object to another sequence type, such as a list, and save the result. So change your:

    my_map = map(...)
    

    to

    my_map = list(map(...))
    

    After that, your code above should work as you expect.

    0 讨论(0)
  • 2020-11-28 16:00

    I faced the same issue since I am using Python 3.7 version. Using list(map(...)) worked. For lower python version using map(...) would work fine, but for higher versions, map returns an iterator pointing to a memory location. So print(...) statement will give the address rather than the items itself. To get the items try using list(map(...))

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