python dict函数枚举对象 [英] python dict function on enumerate object

查看:571
本文介绍了python dict函数枚举对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个枚举对象x,为什么要执行以下操作:

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

dict(x)

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

clear all the items in the enumerate sequence?

推荐答案

枚举创建一个迭代器。迭代器是一个只知道序列的当前项目以及如何获取下一个的python对象,但没有办法重新启动它。因此,一旦你在一个循环中使用了一个迭代器,它就不能给你任何更多的东西,似乎是空的。

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

这篇关于python dict函数枚举对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆