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

yipeiwu_com6年前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学生管理系统

python学生管理系统

这几天开始接触了python语言,这语言相对c语言简洁了不少,语言真是一通百通,学起来还是比较轻松,在熟悉了基本语法,列表(序列),元组以及字典之后写了一个最基础简单的的学生管理系统 能...

对python 矩阵转置transpose的实例讲解

在读图片时,会用到这么的一段代码: image_vector_len = np.prod(image_size)#总元素大小,3*55*47 img = Image.open(pat...

Python facenet进行人脸识别测试过程解析

Python facenet进行人脸识别测试过程解析

1.简介:facenet 是基于 TensorFlow 的人脸识别开源库,有兴趣的同学可以扒扒源代码: https://github.com/davidsandberg/facenet...

pycharm下查看python的变量类型和变量内容的方法

pycharm下查看python的变量类型和变量内容的方法

用过Matlab的同学基本都知道,程序里面的变量内容可以很方便的查看到,但python确没这么方便,对于做数据处理的很不方便,其实不是没有这个功能,只是没有发现而已,今天整理一下供大家相...

使用Python生成200个激活码的实现方法

题目:使用 Python 生成 200 个不重复的激活码 编写思路 # 激活码一般是由26个大写字母和10个数字任意组合而成 # 长度为12位或者16位的居多激活码 # 一个激活码里的字...