enumerate 的用法
enumerate 的用法enumerate 是 Python 內置函數作用是在遍歷可迭代對象時同時獲取索引和值。基本語法enumerate(iterable,start0)返回(index,value)元組start 指定起始索引默認0。 簡單示例 words[Hello,world,this,is,a,test]不用 enumerate手動維護索引i0forwordinwords:print(i,word)i1用 enumerate一行搞定fori,wordinenumerate(words):print(i,word)輸出0Hello1world2this3is4a5test在 Ch02 中的實際用例你打開的文件中就有大量使用構建詞匯表token → ID 映射ch02.ipynb: 把排好序的唯一 token 列表映射為數字vocab{token:integerforinteger,tokeninenumerate(all_words)}效果: {“!”: 0, ‘’: 1, “”: 2, “(”: 3, …}查看詞匯表前 51 項fori,iteminenumerate(vocab.items()):print(item)ifi50:break擴展詞匯表重新編號all_tokenssorted(list(set(preprocessed)))all_tokens.extend([|endoftext|,|unk|])vocab{token:integerforinteger,tokeninenumerate(all_tokens)}|endoftext| → 1130, |unk| → 1131常見模式 場景 寫法 列表 → 字典ID 映射{item:ifori,iteminenumerate(items)}遍歷帶序號fori,valinenumerate(seq):從1開始計數fori,valinenumerate(seq,start1):只取值但記錄位置[ifori,vinenumerate(lst)ifvtarget]對比range(len())? 老式寫法不推薦foriinrange(len(words)):print(i,words[i])? Pythonic 寫法fori,wordinenumerate(words):print(i,word)enumerate更簡潔、更易讀而且適用于任何可迭代對象不僅限于有len()的序列。enumerate詳解1.本質它是一個包裝器# enumerate 不返回列表返回一個迭代器對象words[Hello,world,test]resultenumerate(words)print(result)# enumerate object at 0x...print(type(result))# class enumerate它不是一次性生成所有(index,value)對而是惰性計算——每次next()才產生下一對所以省內存。2.內部工作原理# enumerate 的等價實現簡化版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))# [] — 迭代器耗盡后續為空關鍵理解enumerate對象是一次性的迭代器。這和列表不同 eenumerate([a,b])list(e)# [(0, a), (1, b)]list(e)# [] ← 第一次已經消耗完了3.元組拆包enumerate產生的每個元素是(index,value)元組所以可以三種方式接收forpairinenumerate([x,y]):# pair (0, x)print(pair[0],pair[1])fori,vinenumerate([x,y]):# 直接拆包 ← 最常用print(i,v)fori_v_tupleinenumerate([x,y]):# 如果只想用一個變量i,vi_v_tuple# 手動拆包4.start 參數的實際用途# start1顯示為人類習慣的第 1 行forline_no,textinenumerate(lines,start1):print(f第{line_no}行:{text})# start某個 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.字典推導式詳解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}注意字典推導式中 integer 和 token 的位置值寫在前面 token:integerenumerate產出的 integer 被用作字典的 value。6.常見進階用法 sentenceI HAD always thought Jack.split()# 同時獲取索引、值、值的長度fori,wordinenumerate(sentence):print(i,word,len(word))# 只在特定條件下使用索引target_indices[ifori,wordinenumerate(sentence)ifwordJack]# [3]# enumerate zip 同時遍歷多個序列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.對比所有替代方案 seq[a,b,c]# ? 方式1: range len — Java/C 思維不 Pythonicforiinrange(len(seq)):print(i,seq[i])# ? 方式2: 手動計數器 — 啰嗦容易遺漏 i1i0foriteminseq:print(i,item)i1# ? 方式3: enumerate — 標準寫法fori,iteminenumerate(seq):print(i,item)enumerate的優勢 不需要對象有len()比如文件對象、生成器 不需要支持索引[]比如set、dict.keys() 一行完成不會忘記 i18.常見陷阱# 陷阱1: 在循環中修改列表會導致索引錯亂words[a,b,c]fori,winenumerate(words):ifwb:delwords[i]# ?? 危險enumerate 不知道列表變了# 建議遍歷副本或收集要刪除的索引# 陷阱2: enumerate 不可重復消費eenumerate([1,2,3])list(e)# [(0, 1), (1, 2), (2, 3)]list(e)# [] ← 第二次是空的# 陷阱3: 字典生成時順序沒保證Python 3.6-# Python 3.7 字典保持插入順序所以 vocab {t: i for i, t in enumerate(all_words)}# 中 ID 的分配順序和 all_words 的順序一致一句話總結enumerate(iterable,start0)在遍歷時同時給你索引和值。在 Ch02 里它最重要的用途就是把單詞列表變成{單詞:數字ID}的詞匯表字典。

相關新聞

百度聯盟鏈XuperChain-03-百度聯盟鏈Xuperchain核心概念

百度聯盟鏈XuperChain-03-百度聯盟鏈Xuperchain核心概念

1 高性能一計算能力突破單核、單機的邊界 1.1 性能提升的核心技術 鏈內并行技術(基于自研XVM虛擬機構建DAG)大規模共識技術分叉狀態機技術 系統峰值TPS達8.7w,支撐業務高效運行:2 易開發且可擴展的智能合約開發架構 2.1 百度區塊鏈…

2026/8/2 8:08:00 閱讀更多
2026上海抖音代運營公司實測:B端實體企業避坑篩選與TOP1測評

2026上海抖音代運營公司實測:B端實體企業避坑篩選與TOP1測評

開篇引入:實體企業做抖音的困局與行業濾鏡碎了一地 站在2026年的節點回望,上海及長三角的實體老板們對抖音的情感極其復雜。一邊是平臺上源源不斷的產業帶流量與精準詢盤,另一邊卻是自家賬號“播放量常年卡在500”、“投流燒錢不見響”、“招…

2026/7/30 23:34:11 閱讀更多
網盤直鏈下載助手:徹底告別下載限制的終極解決方案

網盤直鏈下載助手:徹底告別下載限制的終極解決方案

網盤直鏈下載助手:徹底告別下載限制的終極解決方案 【免費下載鏈接】Online-disk-direct-link-download-assistant 一個基于 JavaScript 的網盤文件下載地址獲取工具。基于【網盤直鏈下載助手】修改 ,支持 百度網盤 / 阿里云盤 / 中國移動云盤 / 天翼云盤…

2026/8/2 12:46:09 閱讀更多
Unity游戲開發中MVC框架的實踐指南:從理論到代碼實現

Unity游戲開發中MVC框架的實踐指南:從理論到代碼實現

1. 項目概述:為什么Unity開發者需要關注MVC? 如果你在Unity社區里混跡過一段時間,或者面試過一些Unity相關的崗位,大概率會聽到過“MVC框架”這個詞。它就像一個傳說中的武林秘籍,人人都說好,但真正能把它在…

2026/8/2 12:25:40 閱讀更多
3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南 【免費下載鏈接】GetQzonehistory 獲取QQ空間發布的歷史說說 項目地址: https://gitcode.com/GitHub_Trending/ge/GetQzonehistory 你是否曾想過,那些年發過的QQ空間說說,那些記錄青春的文字…

2026/8/2 0:04:01 閱讀更多
3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南 【免費下載鏈接】GetQzonehistory 獲取QQ空間發布的歷史說說 項目地址: https://gitcode.com/GitHub_Trending/ge/GetQzonehistory 你是否曾想過,那些年發過的QQ空間說說,那些記錄青春的文字…

2026/8/2 0:04:01 閱讀更多
AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O分配PCB板是應用材料(Applied Materials)公司生產的一款用于半導體設備的I/O信號分配電路板。該型號(0100-02186)的核心特點如下:專用于Endura等半導體工藝腔室。集成信號路由與分配功能。連接控制…

2026/8/2 2:51:21 閱讀更多
Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機是日本日清(Nissei)品牌的一款工業用三相異步電機,適用于自動化設備及通用機械驅動。該型號(FFMN-32L-10-T0 40AX)的核心特點如下:三相交流異步電動機。額定…

2026/8/2 2:52:49 閱讀更多