python中迭代器(iterator)的用法
""" 皮蛋编程(https://www.pidancode.com) 创建日期:2022/4/3 功能描述:python中迭代器(iterator)的用法 """ myTuple = (1, 2, 3, 4) myIterator = iter(myTuple) print(next(myIterator)) print(next(myIterator)) print(next(myIterator)) print(next(myIterator)) 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...')
输出:
1
2
3
4
one
two
three
four
Exception caught! Iterator must be empty!
相关文章