[Python] python中迭代器(iterator)的用法 →→→→→进入此内容的聊天室

来自 , 2020-10-25, 写在 Python, 查看 155 次.
URL http://www.code666.cn/view/97ea3cfb
  1. #------------------------------------------------------------------------------
  2. #           Name: iterators.py
  3. #         Author: Kevin Harris
  4. #  Last Modified: 03/11/04
  5. #    Description: This Python script demonstrates how to use iterators.
  6. #------------------------------------------------------------------------------
  7.  
  8. myTuple = (1, 2, 3, 4)
  9. myIterator = iter( myTuple )
  10.  
  11. print( next( myIterator ) )
  12. print( next( myIterator ) )
  13. print( next( myIterator ) )
  14. print( next( myIterator ) )
  15.  
  16. # Becareful, one more call to next() and this script will throw an exception!
  17. #print myIterator.next()
  18.  
  19. print( " " )
  20.  
  21. #------------------------------------------------------------------------------
  22.  
  23. # If you have no idea how many items can be safely accesd via the iterator,
  24. # use a try/except block to keep your script from crashing.
  25.  
  26. myTuple2 = ( "one", "two", "three", "four" )
  27. myIterator2 = iter( myTuple2 )
  28.  
  29. while 1:
  30.     try:
  31.         print( next( myIterator2 ) )
  32.     except StopIteration:
  33.         print( "Exception caught! Iterator must be empty!" )
  34.         break
  35.  
  36. input( '\n\nPress Enter to exit...' )
  37.  
  38. #//python/8094

回复 "python中迭代器(iterator)的用法"

这儿你可以回复上面这条便签

captcha