python-迭代器,產生器

來源:互聯網
上載者:User

標籤:arm   span   isl   協議   eof   tle   ali   tty   enc   

一. 迭代器

        1. 可以使用dir()函數來檢查類的內部定義的函數
         2.特點:
            __iter__() 擷取迭代器
            __next__() 擷取最前面這個元素  

  我們之前?直在?可迭代對象進?迭代操作. 那麼到底什麼是可迭代對象. 本?節主要討
論可迭代對象. ?先我們先回顧?下?前我們所熟知的可迭代對象有哪些:
  str, list, tuple, dict, set. 那為什麼我們可以稱他們為可迭代對象呢? 因為他們都遵循了可
迭代協議. 什麼是可迭代協議. ?先我們先看?段錯誤碼:

# 對的s = "abc"for c in s:    print(c)# 錯的for i in 123:    print(i)結果:Traceback (most recent call last):    File "/Users/sylar/PycharmProjects/oldboy/iterator.py", line 8, in<module>    for i in 123:TypeError: ‘int‘ object is not iterable

  注意看報錯資訊中有這樣?句話. ‘int‘ object is not iterable . 翻譯過來就是整數類型對象
是不可迭代的. iterable表?可迭代的. 表?可迭代協議. 那麼如何進?驗證你的資料類型是否
符合可迭代協議. 我們可以通過dir函數來查看類中定義好的所有?法: 

s = "我的哈哈哈"print(dir(s)) # 可以列印對象中的?法和函數print(dir(str)) # 也可以列印類中聲明的?法和函數

  在列印結果中. 尋找__iter__ 如果能找到. 那麼這個類的對象就是?個可迭代對象 .

[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘,‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘,‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘,‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘,‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘,‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘,‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘,‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘,‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘,‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘,‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘,‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]

  我們發現在字串中可以找到__iter__. 繼續看?下list, tuple, dict, set

print(dir(tuple))print(dir(list))print(dir(open("護?少婦嫩模.txt"))) # ?件對象print(dir(set))print(dir(dict))結果:[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘,‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘,‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘,‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmul__‘,‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘count‘,‘index‘][‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘,‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘,‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘,‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘,‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘,‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘,‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘][‘_CHUNK_SIZE‘, ‘__class__‘, ‘__del__‘, ‘__delattr__‘, ‘__dict__‘,‘__dir__‘, ‘__doc__‘, ‘__enter__‘, ‘__eq__‘, ‘__exit__‘, ‘__format__‘,‘__ge__‘, ‘__getattribute__‘, ‘__getstate__‘, ‘__gt__‘, ‘__hash__‘,‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__lt__‘, ‘__ne__‘,‘__new__‘, ‘__next__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘,‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘_checkClosed‘,‘_checkReadable‘, ‘_checkSeekable‘, ‘_checkWritable‘, ‘_finalizing‘,‘buffer‘, ‘close‘, ‘closed‘, ‘detach‘, ‘encoding‘, ‘errors‘, ‘fileno‘,‘flush‘, ‘isatty‘, ‘line_buffering‘, ‘mode‘, ‘name‘, ‘newlines‘, ‘read‘,‘readable‘, ‘readline‘, ‘readlines‘, ‘seek‘, ‘seekable‘, ‘tell‘,‘truncate‘, ‘writable‘, ‘write‘, ‘writelines‘][‘__and__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘,‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘,‘__hash__‘, ‘__iand__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__ior__‘,‘__isub__‘, ‘__iter__‘, ‘__ixor__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘,‘__ne__‘, ‘__new__‘, ‘__or__‘, ‘__rand__‘, ‘__reduce__‘, ‘__reduce_ex__‘,‘__repr__‘, ‘__ror__‘, ‘__rsub__‘, ‘__rxor__‘, ‘__setattr__‘, ‘__sizeof__‘,‘__str__‘, ‘__sub__‘, ‘__subclasshook__‘, ‘__xor__‘, ‘add‘, ‘clear‘,‘copy‘, 
‘difference‘, ‘difference_update‘, ‘discard‘, ‘intersection‘,‘intersection_update‘, ‘isdisjoint‘, ‘issubset‘, ‘issuperset‘, ‘pop‘,‘remove‘, ‘symmetric_difference‘, ‘symmetric_difference_update‘, ‘union‘,‘update‘][‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘,‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘,‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘,‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘,‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘,‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]

  我們發現這?個可以進?for迴圈的東?都有__iter__函數, 包括range也有. 可以??試?
下.
綜上. 我們可以確定. 如果對象中有__iter__函數. 那麼我們認為這個對象遵守了可迭代協議.
就可以進?迭代. 這?的__iter__是協助我們擷取到對象的迭代器. 我們使?__next__()來擷取
到?個迭代器中的元素. 那麼我們之前講的for的?作原理到底是什麼? 繼續看代碼

s = "我愛北京天安?"c = s.__iter__() # 擷取迭代器print(c.__next__()) # 使?迭代器進?迭代. 擷取?個元素 我print(c.__next__()) # 愛print(c.__next__()) # 北print(c.__next__()) # 京print(c.__next__()) # 天print(c.__next__()) # 安print(c.__next__()) # ?print(c.__next__()) # StopIteration

  我們可以把要迭代的內容當成?彈. 然後呢. 擷取到迭代器__iter__(), 就把?彈都裝在彈夾
中. 然後發射就是__next__()把每?個?彈(元素)打出來. 也就是說, for迴圈的時候. ?開始的
時候是__iter__()來擷取迭代器. 後?每次擷取元素都是通過__next__()來完成的. 當程式遇到
StopIteration將結束迴圈

?. ?成器
  什麼是?成器. ?成器實質就是迭代器.
  在python中有三種?式來擷取?成器:

  1. 通過?成器函數
  2. 通過各種推導式來實現?成器
  3. 通過資料的轉換也可以擷取?成器

 

 

 

 

 

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.