enumerate 的用法

发布时间:2026/7/30 23:44:00

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}的词汇表字典。

相关新闻