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

作者:重负在身 时间:2023-12-16 05:32:51 

本文实例讲述了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,迭代器
0
投稿

猜你喜欢

  • DTS构建组件及其如何完成数据转换服务

    2009-01-20 15:37:00
  • Python数据可视化编程通过Matplotlib创建散点图代码示例

    2022-01-04 17:23:34
  • 详解Python中@staticmethod和@classmethod区别及使用示例代码

    2023-06-03 12:17:20
  • PHP之Mysql常用SQL语句示例的深入分析

    2024-05-05 09:31:21
  • python实现发送和获取手机短信验证码

    2023-08-09 08:02:26
  • Navicat远程连接SQL Server并转换成MySQL步骤详解

    2024-01-14 20:58:48
  • volatile保证可见性及重排序方法

    2022-07-22 03:14:59
  • 解决golang编译提示dial tcp 172.217.160.113:443: connectex: A connection attempt failed(推荐)

    2023-07-16 04:24:49
  • python基础之面对对象基础类和对象的概念

    2021-08-16 03:26:33
  • Perl下应当如何连接Access数据库

    2008-12-04 13:06:00
  • 详细总结Python常见的安全问题

    2022-04-22 14:19:20
  • 安装Python和pygame及相应的环境变量配置(图文教程)

    2023-09-05 15:54:42
  • Python之进行URL编码案例讲解

    2023-03-31 03:46:58
  • Python中的hypot()方法使用简介

    2021-06-02 03:44:37
  • Python环境Pillow( PIL )图像处理工具使用解析

    2022-12-08 16:04:48
  • 详解python 拆包可迭代数据如tuple, list

    2022-01-08 19:28:43
  • python time()的实例用法

    2022-01-09 02:33:02
  • win2003服务器下配置 MySQL 群集(Cluster)的方法

    2024-01-24 17:46:46
  • PyTorch中clone()、detach()及相关扩展详解

    2022-06-29 17:50:34
  • Matlab实现新冠病毒传播模拟效果

    2022-01-23 00:01:28
  • asp之家 网络编程 m.aspxhome.com