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

相关文章

Python matplotlib绘制饼状图功能示例

Python matplotlib绘制饼状图功能示例

本文实例讲述了Python matplotlib绘制饼状图功能。分享给大家供大家参考,具体如下: 一 代码 import numpy as np import matplotlib....

使用python3+xlrd解析Excel的实例

实例如下所示: # -*- coding: utf-8 -*- import xlrd def open_excel(file = 'file.xls'):#打开要解析的Excel文...

浅谈python函数调用返回两个或多个变量的方法

以元祖形式返回  return (a,b,......) 以元祖引用或(x,y,....)接受都可以 为什么不能用列表返回?? 与java一样,列表等属于可变数据类型——由指针...

Python模拟登录之滑块验证码的破解(实例代码)

模拟登录之滑块验证码的破解,具体代码如下所示: # 图像处理标准库 from PIL import Image # web测试 from selenium import webdri...

Python多进程multiprocessing用法实例分析

本文实例讲述了Python多进程multiprocessing用法。分享给大家供大家参考,具体如下: mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核...