【问题标题】:python dict function on enumerate object枚举对象上的python dict函数
【发布时间】:2010-04-26 13:21:38
【问题描述】:

如果我有一个枚举对象 x,为什么要这样做:

dict(x)

清除枚举序列中的所有项目?

【问题讨论】:

  • 请澄清枚举的意思,dict 似乎对我有用:dict(enumerate(['a', 'b', 'c'])) = {0: 'a', 1: 'b', 2: 'c'}

标签: python dictionary enumerate


【解决方案1】:

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

【讨论】:

  • 非常感谢,我需要的解释!
猜你喜欢
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2015-01-23
  • 2017-08-23
  • 2015-08-08
相关资源
最近更新 更多