开发者

How to iterate through an enumerate object and print all the index-item pairs using next() function?

I have the following program

enum1 = enumerate("This is the test string".split())

I need to iterate throug开发者_运维技巧h enum1 and print all the index-item pairs by using next() function.

I try to get the index-item pairs by doing the following

for i in range(len(enum1)):
    print enum1.next()

It throws me an error showing len() can't be applied to an enumeration.

Could anyone suggest me any such way by which I would be able to iterate through this enum to print all the index-item pairs using next() function?

Note: My requirement is to use next() function to retrieve the index-item pairs


simply use:

for i,item in enum1:
   # i is the index
   # item is your item in enum1

or

for i,item in enumerate("This is the test string".split()):
   # i is the index
   # item is your item in enum1

this will use the next method underneath...


Given the weird requirement that you need to use the next() method, you could do

try:
    while True:
        print enum1.next()
except StopIteration:
    pass

You don't know in advance how many items an iterator will yield, so you just have to keep trying to call enum1.next() until the iterator is exhausted.

The usual way to do this is of course

for item in enum1:
    print item

Furthermore, in Python 2.6 or above, calls to the next() method should be replaced by calls to the built-in function next():

print next(enum1)


If you like to keep the exception handler close to the exception you can do it this way

while True:
    try:
        print next(enum1)
    except StopIteration:
        break


Something like:

gen = enumerate((1, 2, 3))
try:
  while True:
    print gen.next()
except StopIteration:
  pass # end of the loop
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜