Python中iter函數(shù)的使用方法-創(chuàng)新互聯(lián)

小編給大家分享一下Python中iter函數(shù)的使用方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

成都創(chuàng)新互聯(lián)公司自2013年起,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目做網(wǎng)站、成都網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元仁和做網(wǎng)站,已為上家服務(wù),為仁和各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18980820575

Python 3中關(guān)于iter (object[, sentinel)] 方法有兩個(gè)參數(shù)。

使用iter (object) 這種形式比較常見,iter (object, sentinel) 這種形式一般較少使用。

1.iter (object)

Python官方文檔對(duì)于這種形式的解釋很容易理解。

此時(shí),object必須是集合對(duì)象,且支持迭代協(xié)議(iteration protocol)或者支持序列協(xié)議(sequence protocol)。

說(shuō)白了,也就是實(shí)現(xiàn)了__iter__() 方法或者 __getitem__() 方法。

l = [1, 2, 3]  for i in iter(l):      print(i)

2.iter (object, sentinel)

Python官方文檔對(duì)于這種形式的解釋是:如果傳遞了第二個(gè)參數(shù),則object必須是一個(gè)可調(diào)用的對(duì)象(如函數(shù))。此時(shí),iter創(chuàng)建了一個(gè)迭代器對(duì)象,每次調(diào)用這個(gè)迭代器對(duì)象的__next__()方法時(shí),都會(huì)調(diào)用object。

如果__next__的返回值等于sentinel,則拋出StopIteration異常,否則返回下一個(gè)值。

   class TestIter(object):        def __init__(self):            self.l=[1,2,3,4,5]            self.i=iter(self.l)        def __call__(self):  #定義了__call__方法的類的實(shí)例是可調(diào)用的            item = next(self.i)            print ("__call__ is called,which would return",item)            return item        def __iter__(self): #支持迭代協(xié)議(即定義有__iter__()函數(shù))            print ("__iter__ is called!!")            return iter(self.l)    t = TestIter()  # t是可調(diào)用的    t1 = iter(t, 3)  # t必須是callable的,否則無(wú)法返回callable_iterator    print(callable(t))    for i in t1:        print(i) # 它每次在調(diào)用的時(shí)候,都會(huì)調(diào)用__call__函數(shù),并且最后輸出3就停止了。 True __call__ is called,which would return 1 1 __call__ is called,which would return 2 2 __call__ is called,which would return 3

在文件讀取時(shí)使用:

import os import hashlib def bytes2human(n):    # 文件大小字節(jié)單位轉(zhuǎn)換    symbols = ('K', 'M', 'G', 'T', 'P', 'E')    prefix = {}    for i, s in enumerate(symbols):        # << 左移” 左移一位表示乘2 即1 << 1=2,二位就表示4 即1 << 2=4,        # 10位就表示1024 即1 << 10=1024 就是2的n次方        prefix[s] = 1 << (i + 1) * 10    for s in reversed(symbols):        if n >= prefix[s]:            value = float(n) / prefix[s]            return '%.2f%s' % (value, s)    return "%sB" % n def get_md5(file_path):    """    得到文件MD5    :param file_path:    :return:    """    if os.path.isfile(file_path):        file_size = os.stat(file_path).st_size        md5_obj = hashlib.md5()  # hashlib        f = open(file_path, 'rb')  # 打開文件        read_size = 0        while read_size < file_size:            read_byte = f.read(8192)            md5_obj.update(read_byte)  # update md5            read_size += len(read_byte)        hash_code = md5_obj.hexdigest()  # get md5 hexdigest        f.close()        print('file: [{}] \nsize: [{}] \nmd5: [{}]'.format(            file_path, bytes2human(read_size), hash_code))        return str(hash_code) def get_filemd5(file_path):    # 使用迭代器讀取文件獲得MD5    if os.path.isfile(file_path):        file_size = os.stat(file_path).st_size        md5_obj = hashlib.md5()  # hashlib        f = open(file_path, 'rb')  # 打開文件        read_size = 1024        for chunk in iter(lambda: f.read(read_size), b''):  # 使用迭代器讀取文件獲得MD5            md5_obj.update(chunk)        hash_code = md5_obj.hexdigest()  # get md5 hexdigest        f.close()        print('file: [{}] \nsize: [{}] \nmd5: [{}]'.format(            file_path, bytes2human(file_size), hash_code))        return str(hash_code) if __name__ == '__main__':    md5 = get_md5(        r'C:\README.md')    md5_1 = get_filemd5(        r'C:\README.md') ------------------------輸出 file: [C:\README.md] size: [941B] md5: [d22b8f76dcd8cfbfd4669d9d8101077e] file: [C:\README.md] size: [941B] md5: [d22b8f76dcd8cfbfd4669d9d8101077e]

以上是Python中iter函數(shù)的使用方法的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道!

名稱欄目:Python中iter函數(shù)的使用方法-創(chuàng)新互聯(lián)
URL網(wǎng)址:http://muchs.cn/article8/cdceop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、網(wǎng)站內(nèi)鏈、移動(dòng)網(wǎng)站建設(shè)、做網(wǎng)站網(wǎng)站維護(hù)、全網(wǎng)營(yíng)銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化