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

前端 未结 3 1960
轮回少年
轮回少年 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']
    

提交回复
热议问题