comparator比较器用法_Python学习:好像很少人知道 Python iter() 的另外一个用法?...
在前面的一期Python學習教程有跟大家介紹過關于序列、可迭代對象、迭代器、生成器的概念,其中有提到過,如果實現了 _iter_() 和 _next_() 就是生成器,同時驗證可迭代對象最好的方法是 iter(obj) 。
今天我們來介紹下 iter() 方法另外的用法。
據說是很少有人知道這個用法
一、上代碼、學用法
我們都比較熟悉 iter(obj),會返現一個迭代器,如果 obj 不是可迭代對象,則會報錯。但其實如果仔細看官方文檔,會發現 iter() 方法其實是接受兩個參數的,文檔說明如下
iter(object[, sentinel])sentinel 英文翻譯為 哨兵。
sentinel 參數是可選的,當它存在時,object 不再傳入一個可迭代對象,而是一個可調用對象,通俗點說就是可以通過()調用的對象,而 sentinel 的作用就和它的翻譯一樣,是一個“哨兵”,當時可調用對象返回值為這個“哨兵”時,循環結束,且不會輸出這個“哨兵”。
可能有點難懂,用一個簡單需求來說明,需求說明如下:
心里想一個[1, 10]范圍的數,然后代碼開始隨機,當隨機到想的數時停止,看每次代碼需要隨機幾次。
實現分析:看起來應該很簡單,random,然后加一個if判斷即可,但是用 iter() 來實現更簡單。實現代碼如下:
from random import randint def guess():return randint(0, 10) num = 1 # 這里先寫死心里想的數為5 for i in iter(guess, 5):print("第%s次猜測,猜測數字為: %s" % (num, i))num += 1 # 當 guess 返回的是 5 時,會拋出異常 StopIteration,但 for 循環會處理異常,即會結束循環二、還是看看文檔吧
關于這兩個參數,文檔里也說的很詳細,分段解釋如下:
The first argument is interpreted very differently depending on the presence of the second argument.翻譯:第一個參數根據第二個參數有不同的含義
Without a second argument, object must be a collection object which supports the iteration protocol (the _iter_() method), or it must support the sequence protocol (the _getitem_() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised.翻譯:如果沒有第二個參數,object(即第一個參數)是一個支持迭代器協議(實現_iter_()方法的)的集合對象,或者是支持序列協議(實現_getitem_()方法)且是從0開始索引。如果它不支持其中任何一個,則拋出 TypeError 異常
簡單來說就是,如果沒有第二個參數,就是我們比較熟悉的用法。代碼示例如下:
In [5]: iter("123") Out[5]: <str_iterator at 0x105c9b9e8> In [6]: iter([1, 2, 3]) Out[6]: <list_iterator at 0x105f9f8d0> In [7]: iter(123) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-c76acad08c3c> in <module>() ----> 1 iter(123) TypeError: 'int' object is not iterable再來看看有第二個參數的情況
If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its _next_() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.翻譯:如果給定了第二個參數 sentinel,object 則必須是一個可調用對象,這個可調用對象沒有任何參數,當可調用對象的返回值等于 sentinel 的值時,拋出 StopIteration 的異常,否則返回當前值。(這里如果不好理解可調用對象,可以理解為函數,這樣更容易想明白)
對于這個用法的適用場景,文檔中也給出了說明:
One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:翻譯:對于第二個參數,一個有用的場景是創建一個 blokc-reader,即根據條件中斷讀取。比如:從二進制數據庫文件讀取固定寬度的塊,直到到達文件的末尾,代碼示例如下:
from functools import partial with open('mydata.db', 'rb') as f:for block in iter(partial(f.read, 64), b''):process_block(block)三、小結一下
1、iter() 方法不管有沒有第二個參數,返回的都是迭代器
2、iter() 方法第一個參數的參數類型,根據有無第二個參數決定
其實關于Python學習有很多還有待發掘的用法和方法,歡迎各位小伙伴補充呀!更多的Python學習教程也會繼續為大家更新!
總結
以上是生活随笔為你收集整理的comparator比较器用法_Python学习:好像很少人知道 Python iter() 的另外一个用法?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何赚钱打字电脑如何赚钱的方法
- 下一篇: python public_【速记速学】