python中迭代器(iterator)用法實例分析
更新時間:2015年04月29日 09:39:34 作者:重負在身
這篇文章主要介紹了python中迭代器(iterator)用法,實例分析了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 GUI庫圖形界面開發(fā)之PyQt5信號與槽多窗口數(shù)據(jù)傳遞詳細使用方法與實例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5信號與槽多窗口數(shù)據(jù)傳遞詳細使用方法與實例,需要的朋友可以參考下2020-03-03
python命令行引導用戶填寫可用的ip地址和端口號實現(xiàn)
這篇文章主要為大家介紹了python命令行引導用戶填寫可用的ip地址和端口號實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11

