python dict function on enumerate object

这一生的挚爱 提交于 2019-12-01 18:53:07

问题


If I have an enumerate object x, why does doing the following:

dict(x)

clear all the items in the enumerate sequence?


回答1:


enumerate creates an iterator. A iterator is a python object that only knows about the current item of a sequence and how to get the next, but there is no way to restart it. Therefore, once you have used a iterator in a loop, it cannot give you any more items and appears to be empty.

If you want to create a real sequence from a iterator you can call list on it.

stuff = range(5,0,-1)
it = enumerate(stuff)
print dict(it), dict(it) # first consumes all items, so there are none left for the 2nd call

seq = list(enumerate(stuff)) # creates a list of all the items
print dict(seq), dict(seq) # you can use it as often as you want


来源:https://stackoverflow.com/questions/2713712/python-dict-function-on-enumerate-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!