Python 如何使用next()函数遍历枚举对象并打印所有索引项对?
我有以下程序Python 如何使用next()函数遍历枚举对象并打印所有索引项对?,python,Python,我有以下程序 enum1 = enumerate("This is the test string".split()) 我需要遍历enum1,并使用next()函数打印所有索引项对 我尝试通过执行以下操作来获得索引项对 for i in range(len(enum1)): print enum1.next() 它向我抛出一个错误,显示len()无法应用于枚举 有没有人能建议我使用next()函数迭代此枚举以打印所有索引项对的方法 注意:我的要求是使用next()函数检索索引项对鉴于
enum1 = enumerate("This is the test string".split())
我需要遍历enum1,并使用next()函数打印所有索引项对
我尝试通过执行以下操作来获得索引项对
for i in range(len(enum1)):
print enum1.next()
它向我抛出一个错误,显示len()
无法应用于枚举
有没有人能建议我使用next()
函数迭代此枚举以打印所有索引项对的方法
注意:我的要求是使用
next()
函数检索索引项对鉴于需要使用next()
方法的奇怪要求,您可以这样做
try:
while True:
print enum1.next()
except StopIteration:
pass
您事先不知道迭代器将产生多少项,因此您只需继续尝试调用enum1.next()
,直到迭代器耗尽为止
通常的做法当然是
for item in enum1:
print item
此外,在Python 2.6或更高版本中,对next()
方法的调用应替换为对内置函数next()
的调用:
只需使用:
for i,item in enum1:
# i is the index
# item is your item in enum1
或
这将使用下面的next
方法…类似于:
gen = enumerate((1, 2, 3))
try:
while True:
print gen.next()
except StopIteration:
pass # end of the loop
如果您想让异常处理程序靠近异常,可以这样做
while True:
try:
print next(enum1)
except StopIteration:
break
这是一个奇怪的要求。当for循环更好时,为什么必须使用next()。@gnibller:我认为Ava无法回答,甚至还没有SO帐户。有人知道如何重新访问迁移的问题吗?我认为这并不能回答问题:她想要得到索引和项目。她应该重复计算,如我下面的回答所示。@rafalotufo:这使用问题中定义的
enum1
,因此这将始终生成索引和项目。此外,我非常确定OP希望显式使用next()
(无论出于何种原因)。
gen = enumerate((1, 2, 3))
try:
while True:
print gen.next()
except StopIteration:
pass # end of the loop
while True:
try:
print next(enum1)
except StopIteration:
break