python中迭代器(iterator)用法实例分析

本文实例讲述了python中迭代器(iterator)用法。分享给大家供大家参考。具体如下:

#—————————————
# name: iterators.py
# author: kevin harris
# last modified: 03/11/04
# description: this python script demonstrates how to use iterators.
#—————————————
mytuple = (1, 2, 3, 4)
myiterator = iter( mytuple )
print( next( myiterator ) )
print( next( myiterator ) )
print( next( myiterator ) )
print( next( myiterator ) )
# becareful, one more call to next()
# and this script will throw an exception!
#print myiterator.next()
print( ” ” )
#—————————————
# if you have no idea how many items
# can be safely accesd via the iterator,
# use a try/except block to keep your script from crashing.
mytuple2 = ( “one”, “two”, “three”, “four” )
myiterator2 = iter( mytuple2 )
while 1:
try:
print( next( myiterator2 ) )
except stopiteration:
print( “exception caught! iterator must be empty!” )
break
input( ‘\n\npress enter to exit…’ )

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论