2010-04-26 157 views
4

如果我有一個枚舉對象x,爲什麼執行以下操作:蟒蛇字典功能

dict(x) 

清除所有的枚舉順序的項目?

+4

請說明您羅列的意思,字典似乎工作文件對我來說吧: '字典(枚舉([ '一', 'B', 'C']))= {0: 'a',1:'b',2:'c'}' – 2010-04-26 13:33:10

回答

18

enumerate創建iterator。迭代器是一個只知道序列當前項目以及如何獲得下一個序列的python對象,但無法重新啓動它。因此,一旦你在一個循環中使用了一個迭代器,它就不能再給你任何更多的項目,並且看起來是空的。

如果你想從一個迭代器創建一個真實的序列,你可以在其上調用list

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 
+0

非常感謝,我需要的解釋! – cockadoodledo 2010-04-26 14:00:07