python中迭代器(iterator)用法实例分析
更新时间:2015年04月29日 09:39:34 作者:重负在身
这篇文章主要介绍了python中迭代器(iterator)用法,实例分析了Python中迭代器的相关使用技巧,非常具有实用价值,需要的朋友可以参考下
本文实例讲述了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程序设计有所帮助。
相关文章
Appium+python+unittest搭建UI自动化框架的实现
本文主要介绍了Appium+python+unittest搭建UI自动化框架的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-03-03
关于Python中的if __name__ == __main__详情
在学习Python的过程中发现即使把if __name__ == ‘__main__’ 去掉,程序还是照样运行。很多小伙伴只知道是这么用的,也没有深究具体的作用。这篇文字就来介绍一下Python中的if __name__ == ‘__main__’的作用,需要的朋友参考下文2021-09-09
Python3+OpenCV2实现图像的几何变换(平移、镜像、缩放、旋转、仿射)
这篇文章主要介绍了Python3+OpenCV2实现图像的几何变换(平移、镜像、缩放、旋转、仿射),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-05-05


最新评论