如何使用next()函数遍历枚举对象并打印所有索引-项对?
我有一个这样的程序
enum1 = enumerate("This is the test string".split())
我需要遍历enum1,并使用next()函数打印出所有的索引-项对。
我尝试通过以下方式获取索引-项对
for i in range(len(enum1)):
print enum1.next()
但是出现了一个错误,提示len()
不能用于枚举类型。
有没有人能建议我一种方法,让我可以使用next()
函数遍历这个枚举,并打印出所有的索引-项对呢?
注意:我需要使用next()
函数来获取索引-项对。
4 个回答
2
如果你想把异常处理器放在离异常发生的地方更近一些,可以这样做:
while True:
try:
print next(enum1)
except StopIteration:
break
4
根据这个奇怪的要求,你需要使用 next()
方法,你可以这样做:
try:
while True:
print enum1.next()
except StopIteration:
pass
你不知道一个迭代器会产生多少个项目,所以你只能不断尝试调用 enum1.next()
,直到迭代器没有更多的项目为止。
通常的做法是:
for item in enum1:
print item
此外,在 Python 2.6 或更高版本中,调用 next()
方法的方式应该改为使用内置的 next()
函数:
print next(enum1)
6
简单使用:
for i,item in enum1:
# i is the index
# item is your item in enum1
或者
for i,item in enumerate("This is the test string".split()):
# i is the index
# item is your item in enum1
这样做会在底层使用 next
方法...