溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python iter()的用法有哪些

發(fā)布時(shí)間:2021-11-20 16:30:36 來(lái)源:億速云 閱讀:146 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容主要講解“Python iter()的用法有哪些”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Python iter()的用法有哪些”吧!

一、上代碼、學(xué)用法

我們都比較熟悉 iter(obj),會(huì)返現(xiàn)一個(gè)迭代器,如果 obj 不是可迭代對(duì)象,則會(huì)報(bào)錯(cuò)。但其實(shí)如果仔細(xì)看官方文檔,會(huì)發(fā)現(xiàn) iter() 方法其實(shí)是接受兩個(gè)參數(shù)的,文檔說(shuō)明如下

iter(object[, sentinel])

sentinel 英文翻譯為 哨兵。

sentinel 參數(shù)是可選的,當(dāng)它存在時(shí),object 不再傳入一個(gè)可迭代對(duì)象,而是一個(gè)可調(diào)用對(duì)象,通俗點(diǎn)說(shuō)就是可以通過(guò)()調(diào)用的對(duì)象,而 sentinel 的作用就和它的翻譯一樣,是一個(gè)“哨兵”,當(dāng)時(shí)可調(diào)用對(duì)象返回值為這個(gè)“哨兵”時(shí),循環(huán)結(jié)束,且不會(huì)輸出這個(gè)“哨兵”。

可能有點(diǎn)難懂,用一個(gè)簡(jiǎn)單需求來(lái)說(shuō)明,需求說(shuō)明如下:

心里想一個(gè)[1, 10]范圍的數(shù),然后代碼開始隨機(jī),當(dāng)隨機(jī)到想的數(shù)時(shí)停止,看每次代碼需要隨機(jī)幾次。

實(shí)現(xiàn)分析:看起來(lái)應(yīng)該很簡(jiǎn)單,random,然后加一個(gè)if判斷即可,但是用 iter() 來(lái)實(shí)現(xiàn)更簡(jiǎn)單。實(shí)現(xiàn)代碼如下:

from random import randint
def guess():
 return randint(0, 10)
num = 1
# 這里先寫死心里想的數(shù)為5
for i in iter(guess, 5):
 print("第%s次猜測(cè),猜測(cè)數(shù)字為: %s" % (num, i))
 num += 1
# 當(dāng) guess 返回的是 5 時(shí),會(huì)拋出異常 StopIteration,但 for 循環(huán)會(huì)處理異常,即會(huì)結(jié)束循環(huán)

二、還是看看文檔吧

關(guān)于這兩個(gè)參數(shù),文檔里也說(shuō)的很詳細(xì),分段解釋如下:

The first argument is interpreted very differently depending on the presence of the second argument.

翻譯:第一個(gè)參數(shù)根據(jù)第二個(gè)參數(shù)有不同的含義

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.

翻譯:如果沒(méi)有第二個(gè)參數(shù),object(即第一個(gè)參數(shù))是一個(gè)支持迭代器協(xié)議(實(shí)現(xiàn)_iter_()方法的)的集合對(duì)象,或者是支持序列協(xié)議(實(shí)現(xiàn)_getitem_()方法)且是從0開始索引。如果它不支持其中任何一個(gè),則拋出 TypeError 異常

簡(jiǎn)單來(lái)說(shuō)就是,如果沒(méi)有第二個(gè)參數(shù),就是我們比較熟悉的用法。代碼示例如下:

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

再來(lái)看看有第二個(gè)參數(shù)的情況

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.

翻譯:如果給定了第二個(gè)參數(shù) sentinel,object 則必須是一個(gè)可調(diào)用對(duì)象,這個(gè)可調(diào)用對(duì)象沒(méi)有任何參數(shù),當(dāng)可調(diào)用對(duì)象的返回值等于 sentinel 的值時(shí),拋出 StopIteration 的異常,否則返回當(dāng)前值。(這里如果不好理解可調(diào)用對(duì)象,可以理解為函數(shù),這樣更容易想明白)

對(duì)于這個(gè)用法的適用場(chǎng)景,文檔中也給出了說(shuō)明:

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:

翻譯:對(duì)于第二個(gè)參數(shù),一個(gè)有用的場(chǎng)景是創(chuàng)建一個(gè) blokc-reader,即根據(jù)條件中斷讀取。比如:從二進(jìn)制數(shù)據(jù)庫(kù)文件讀取固定寬度的塊,直到到達(dá)文件的末尾,代碼示例如下:

from functools import partial
with open('mydata.db', 'rb') as f:
 for block in iter(partial(f.read, 64), b''):
 process_block(block)

到此,相信大家對(duì)“Python iter()的用法有哪些”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI