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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

pyqt 实现在Widgets中显示图片和文字的方法

pyqt 实现在Widgets中显示图片和文字的方法

思路非常简单:<p>创建window,设置窗口大小,创建label1,导入图片,创建label2,导入文字,show,结束!</p> import sys...

python将excel转换为csv的代码方法总结

python:如何将excel文件转化成CSV格式 import pandas as pd data = pd.read_excel('123.xls','Sheet1',index...

python3.5 + PyQt5 +Eric6 实现的一个计算器代码

python3.5 + PyQt5 +Eric6 实现的一个计算器代码

目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0,学了半天就做出来个这么个结果,bug不少。 python3.5 + PyQt5 +Eric6 在windows7 32位系统...

Linux中安装Python的交互式解释器IPython的教程

IPython是Python的交互式Shell,提供了代码自动补完,自动缩进,高亮显示,执行Shell命令等非常有用的特性。特别是它的代码补完功能,例如:在输入zlib.之后按下Tab键...

python 实现将字典dict、列表list中的中文正常显示方法

在代码文件中定义中文时,经常会遇到问题,要么编码错误,要么是无法正常打印显示。 例如,dict_chinese.py: #!/usr/bin/python a={'name': 'f...