python迭代器,python代器

來源:互聯網
上載者:User

python迭代器,python代器
可直接作用於for迴圈的對象叫做可迭代對象(iterable);可被next()函數調用並不斷返回下一個值的對象稱為迭代器(iterator);所有的可迭代對象均可以通過內建函數iter()來轉變為迭代器。在使用for迴圈的時候,程式就會自動調用即將處理的對象的迭代器對象,然後使用它的next()方法,直到檢測一個stoplteration異常。

>>> l = [4,5,6,7,8,9,0]   #這是一個列表
>>> i = iter(l)                 #可迭代對象轉換為迭代器;
>>> next(i)
4
>>> next(i)
5
>>> next(i)
6
>>> next(i)
7
>>> next(i)
8
>>> next(i)
9
>>> next(i)
0
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

因為列表中麼有超過0的數字,所以當範圍超過的話,就會返回一個StopIteration異常。

在生產環境中如何判斷呢

>>> L = [4,5,6]
>>> I = L.__iter__()
>>> L.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__next__'
>>> I.__next__()
4
>>> from collections import Iterator, Iterable
>>> isinstance(L, Iterable)
True
>>> isinstance(L, Iterator)
False
>>> isinstance(I, Iterable)
True
>>> isinstance(I, Iterator)
True
>>> [x**2 for x in I]
[25, 36]

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.