python之旅:迭代器

來源:互聯網
上載者:User

標籤:一件事   list   可迭代對象   lin   end   賦值   獲得   停止   ict   

1、什麼是迭代器?

迭代器是一個重複的過程,並且每次重複都是機遇上一次的結果而來

要想瞭解迭代器到底是什嗎?必須先瞭解一個概念,即什麼是可迭代的對象?

可迭代對象:在python中,但凡內建有__iter__方法的對象,都是可迭代對象

以下都是可迭代的對象: ( 你可以自己在對象後面 ._ 看下有沒有__iter__ )str=‘hello‘list=[1,2,3]tup={1,2,3}dic={‘x‘:1}s1={‘a‘,‘b‘,‘c‘}f=open(‘a.txt‘,‘w‘,encoding=‘utf-8‘)

 

2、迭代器

迭代器:迭代取值工具,可迭代的對象執行__iter__方法得到的傳回值就是迭代器對象

dic={‘x‘:1,‘y‘:2,‘z‘:3}iter_dic=dic.__iter__()     #第一件事是獲得一個可迭代器,即調用了__iter__()函數print(iter_dic.__next__())  #第二件事是迴圈的過程,迴圈調用__next__()函數。print(iter_dic.__next__())print(iter_dic.__next__())
print(iter_dic.__next__()) #第四行會提示哦,也相當於報錯,只有三個值,你取第四個值的時候會停止迭代
                #    print(iter_dic.__next__())
                  StopIteratio
4、可迭代的對象vs迭代器對象?
可迭代的對象:str,list,tuple,dict,set,file
  1、擷取可迭代對象的方式:python內建的有str,list,tuple,dict,set,file都是可迭代對象

  2、特點:內建有__iter__方法的都叫可迭代的對象,執行該方法會拿到一個迭代器對象。
 迭代器對象:檔案對象本身就是迭代器對象
  1、擷取迭代器對象的方式:
        執行可迭代對象的__iter__方法,拿到的傳回值就是迭代器對象
  2、特點:
        內建有__next__方法,執行該方法會拿到迭代器對象中的一個值
        內建有__iter__方法,執行該方法會拿到迭代器本身
str1=‘hello‘list1=[1,2,3]tup1=(1,2,3)dic={‘x‘:1}s1={‘a‘,‘b‘,‘c‘}#檔案本身就是迭代器對象f=open(‘a.txt‘,‘w‘,encoding=‘utf-8‘)f.__next__()
5、迭代器的優缺點分析

迭代器的優點:

       提供了一種可不依賴於索引的取值方式

       迭代器更加節省記憶體

迭代器的缺點:

       取值麻煩,只能一個一個取,只能往後取

       並且是一次性的,無法用len擷取長度

1、提供了一種可不依賴於索引的取值方式
#這是a.txt檔案的內容adadaaasdasddasdasdasl=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)iter=l.__iter__()while True: #死迴圈 try: #用這個參數來檢測 print(iter.__next__(),end=‘‘) except StopIteration: #檢測什麼時候出現StopIteration break #監測到出現StopIteration 就break
l.close()
#結果如下
adadaaasdasd
dasdas
das
#沒有報錯

2、迭代器更加節省記憶體
item=range(0,100000000000000000000000000000000000000000000)  #如rang,python2中會依次列印1,2,3,4,5,6.。。。python3中最佳化了迭代器直接列印出來,所以更省記憶體

print(item)
#結果如下
range(0, 100000000000000000000000000000000000000000000)
#取值麻煩,只能一個一個取,只能往後取x=[1,2,3]iter_x=x.__iter__()while True:    try:        print(iter_x.__next__())    except StopIteration:        breakprint(‘第二次=================================》‘)iter_x=x.__iter__()while True:    try:        print(iter_x.__next__())    except StopIteration:        break#結果如下123第二次=================================》123
6、for迴圈原理分析:
#6.1、for 迴圈稱之為迭代器迴圈,in後跟的必須是可迭代的對象#6.2、for迴圈會執行in後對象的__iter__方法,拿到迭代器對象#6.3、然後調用迭代器對象的__next__方法,拿到一個傳回值賦值給line,執行一次迴圈體#6.4、周而復始,直到取值完畢,for迴圈會檢測到異常自動結束迴圈l=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)for line in l: #iter_l=l.__iter__()    print(line,end=‘‘)for item in {‘x‘:1,‘y‘:2}:    print(item,end=‘‘)#結果如下adadaaasdasddasdasdasxy

 

python之旅:迭代器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.