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实现基于TCP UDP协议的IPv4 IPv6模式客户端和服务端功能示例

本文实例讲述了Python实现基于TCP UDP协议的IPv4 IPv6模式客户端和服务端功能。分享给大家供大家参考,具体如下: 由于目前工作的需要,需要在IPv4和IPv6两种网络模式...

python MNIST手写识别数据调用API的方法

python MNIST手写识别数据调用API的方法

MNIST数据集比较小,一般入门机器学习都会采用这个数据集来训练 下载地址:yann.lecun.com/exdb/mnist/ 有4个有用的文件: train-images-idx3...

Python利用itchat对微信中好友数据实现简单分析的方法

Python利用itchat对微信中好友数据实现简单分析的方法

前言 最近在一个微信公众号上看到一个调用微信 API 可以对微信好友进行简单数据分析的一个包 itchat 感觉挺好用的,就简单尝试了一下。 库文档说明链接在这: itchat 安装 在...

Python 分析Nginx访问日志并保存到MySQL数据库实例

使用Python 分析Nginx access 日志,根据Nginx日志格式进行分割并存入MySQL数据库。一、Nginx access日志格式如下:复制代码 代码如下:$remote_...

python 实现判断ip连通性的方法总结

python 以下是个人学习 python 研究判断ip连通性方法的集合。 缺点可能有办法解决,如有错误,欢迎矫正。 方法一 import os return1=os.system(...