python中迭代器(iterator)用法實(shí)例分析
更新時(shí)間:2015年04月29日 09:39:34 作者:重負(fù)在身
這篇文章主要介紹了python中迭代器(iterator)用法,實(shí)例分析了Python中迭代器的相關(guān)使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了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...' )
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5信號(hào)與槽多窗口數(shù)據(jù)傳遞詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5信號(hào)與槽多窗口數(shù)據(jù)傳遞詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-03-03快速解決pandas.read_csv()亂碼的問(wèn)題
今天小編就為大家分享一篇快速解決pandas.read_csv()亂碼的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06python命令行引導(dǎo)用戶填寫可用的ip地址和端口號(hào)實(shí)現(xiàn)
這篇文章主要為大家介紹了python命令行引導(dǎo)用戶填寫可用的ip地址和端口號(hào)實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11