
enumerate 的用法enumerate 是 Python 內(nèi)置函數(shù)作用是在遍歷可迭代對(duì)象時(shí)同時(shí)獲取索引和值?;菊Z(yǔ)法enumerate(iterable,start0)返回(index,value)元組start 指定起始索引默認(rèn)0。 簡(jiǎn)單示例 words[Hello,world,this,is,a,test]不用 enumerate手動(dòng)維護(hù)索引i0forwordinwords:print(i,word)i1用 enumerate一行搞定fori,wordinenumerate(words):print(i,word)輸出0Hello1world2this3is4a5test在 Ch02 中的實(shí)際用例你打開(kāi)的文件中就有大量使用構(gòu)建詞匯表token → ID 映射ch02.ipynb: 把排好序的唯一 token 列表映射為數(shù)字vocab{token:integerforinteger,tokeninenumerate(all_words)}效果: {“!”: 0, ‘’: 1, “”: 2, “(”: 3, …}查看詞匯表前 51 項(xiàng)fori,iteminenumerate(vocab.items()):print(item)ifi50:break擴(kuò)展詞匯表重新編號(hào)all_tokenssorted(list(set(preprocessed)))all_tokens.extend([|endoftext|,|unk|])vocab{token:integerforinteger,tokeninenumerate(all_tokens)}|endoftext| → 1130, |unk| → 1131常見(jiàn)模式 場(chǎng)景 寫(xiě)法 列表 → 字典ID 映射{item:ifori,iteminenumerate(items)}遍歷帶序號(hào)fori,valinenumerate(seq):從1開(kāi)始計(jì)數(shù)fori,valinenumerate(seq,start1):只取值但記錄位置[ifori,vinenumerate(lst)ifvtarget]對(duì)比range(len())? 老式寫(xiě)法不推薦foriinrange(len(words)):print(i,words[i])? Pythonic 寫(xiě)法fori,wordinenumerate(words):print(i,word)enumerate更簡(jiǎn)潔、更易讀而且適用于任何可迭代對(duì)象不僅限于有l(wèi)en()的序列。enumerate詳解1.本質(zhì)它是一個(gè)包裝器# enumerate 不返回列表返回一個(gè)迭代器對(duì)象words[Hello,world,test]resultenumerate(words)print(result)# enumerate object at 0x...print(type(result))# class enumerate它不是一次性生成所有(index,value)對(duì)而是惰性計(jì)算——每次next()才產(chǎn)生下一對(duì)所以省內(nèi)存。2.內(nèi)部工作原理# enumerate 的等價(jià)實(shí)現(xiàn)簡(jiǎn)化版defmy_enumerate(iterable,start0):countstartforiteminiterable:yield(count,item)count1# 因此可以這樣拆解eenumerate([a,b,c])print(next(e))# (0, a)print(next(e))# (1, b)print(next(e))# (2, c)print(list(e))# [] — 迭代器耗盡后續(xù)為空關(guān)鍵理解enumerate對(duì)象是一次性的迭代器。這和列表不同 eenumerate([a,b])list(e)# [(0, a), (1, b)]list(e)# [] ← 第一次已經(jīng)消耗完了3.元組拆包enumerate產(chǎn)生的每個(gè)元素是(index,value)元組所以可以三種方式接收f(shuō)orpairinenumerate([x,y]):# pair (0, x)print(pair[0],pair[1])fori,vinenumerate([x,y]):# 直接拆包 ← 最常用print(i,v)fori_v_tupleinenumerate([x,y]):# 如果只想用一個(gè)變量i,vi_v_tuple# 手動(dòng)拆包4.start 參數(shù)的實(shí)際用途# start1顯示為人類習(xí)慣的第 1 行forline_no,textinenumerate(lines,start1):print(f第{line_no}行:{text})# start某個(gè) ID 偏移量特殊 token 接在詞匯表后面all_tokens[!,A,the]# 0~2all_tokens.extend([|unk|])# 索引 3vocab{t:ifori,tinenumerate(all_tokens)}# {!: 0, A: 1, the: 2, |unk|: 3}5.字典推導(dǎo)式詳解Ch02 核心模式 all_words[!,,,the,hello]vocab{token:integerforinteger,tokeninenumerate(all_words)}# ↑key ↑value ↑index ↑item# 一步步拆解# 第 1 輪: integer0, token! → {!: 0}# 第 2 輪: integer1, token → {: 1}# 第 3 輪: integer2, token → {: 2}# 第 4 輪: integer3, tokenthe → {the: 3}# 第 5 輪: integer4, tokenhello → {hello: 4}注意字典推導(dǎo)式中 integer 和 token 的位置值寫(xiě)在前面 token:integerenumerate產(chǎn)出的 integer 被用作字典的 value。6.常見(jiàn)進(jìn)階用法 sentenceI HAD always thought Jack.split()# 同時(shí)獲取索引、值、值的長(zhǎng)度f(wàn)ori,wordinenumerate(sentence):print(i,word,len(word))# 只在特定條件下使用索引target_indices[ifori,wordinenumerate(sentence)ifwordJack]# [3]# enumerate zip 同時(shí)遍歷多個(gè)序列a[a,b,c]b[1,2,3]fori,(x,y)inenumerate(zip(a,b)):print(f[{i}]{x}-{y})# 嵌套 enumeratematrix[[a1,a2],[b1,b2]]forrow_idx,rowinenumerate(matrix):forcol_idx,valinenumerate(row):print(f({row_idx},{col_idx}):{val})# (0,0): a1 (0,1): a2 (1,0): b1 (1,1): b27.對(duì)比所有替代方案 seq[a,b,c]# ? 方式1: range len — Java/C 思維不 Pythonicforiinrange(len(seq)):print(i,seq[i])# ? 方式2: 手動(dòng)計(jì)數(shù)器 — 啰嗦容易遺漏 i1i0foriteminseq:print(i,item)i1# ? 方式3: enumerate — 標(biāo)準(zhǔn)寫(xiě)法fori,iteminenumerate(seq):print(i,item)enumerate的優(yōu)勢(shì) 不需要對(duì)象有l(wèi)en()比如文件對(duì)象、生成器 不需要支持索引[]比如set、dict.keys() 一行完成不會(huì)忘記 i18.常見(jiàn)陷阱# 陷阱1: 在循環(huán)中修改列表會(huì)導(dǎo)致索引錯(cuò)亂words[a,b,c]fori,winenumerate(words):ifwb:delwords[i]# ?? 危險(xiǎn)enumerate 不知道列表變了# 建議遍歷副本或收集要?jiǎng)h除的索引# 陷阱2: enumerate 不可重復(fù)消費(fèi)eenumerate([1,2,3])list(e)# [(0, 1), (1, 2), (2, 3)]list(e)# [] ← 第二次是空的# 陷阱3: 字典生成時(shí)順序沒(méi)保證Python 3.6-# Python 3.7 字典保持插入順序所以 vocab {t: i for i, t in enumerate(all_words)}# 中 ID 的分配順序和 all_words 的順序一致一句話總結(jié)enumerate(iterable,start0)在遍歷時(shí)同時(shí)給你索引和值。在 Ch02 里它最重要的用途就是把單詞列表變成{單詞:數(shù)字ID}的詞匯表字典。