开发者

Using an iterator to print integers

What I want to do is print the integers 0 through 5 in the code below but all I get is an address of the iterator?

def main():

    l = []
    开发者_如何学Gofor i in range(0,5):
        l.append(i)

    it = iter(l)

    for i in range(0,5):
        print it
        it.next()

if __name__ == '__main__':
    main()


To access the values returned by an iterator, you use the next() method of the iterator like so:

try:
    while True:
        val = it.next()
        print(val)
except StopIteration:
    print("Iteration done.")

next() has both the purpose of advancing the iterator and returning the next element. StopIteration is thrown when iteration is done.

Since this is quite cumbersome, all of this is wrapped nicely up in the for-syntax:

for i in it:
    print(i)
print("Iteration done.")

More links:

  • Python documentation on iterator.


When you have an iterator, you have to iterate over it, not over a range.

for i in it:
    print(i)


When you are using the for loop, you are actually calling the iterator object's __next__ method implicitly. So, you would just not use something like range, but instead just use iterator itself.

for i in it:
    print i

For what it is worth, xrange in Python 2 and range in Python 3 returns an iterator, so you just write your first loop with those to have your desired solution,

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜