enumerate 的用法
enumerate 的用法
enumerate 是 Python 内置函数,作用是在遍历可迭代对象时,同时获取索引和值。
基本语法enumerate(iterable,start=0)返回(index,value)元组,start 指定起始索引(默认0)。 简单示例 words=["Hello","world","this","is","a","test"]不用 enumerate:手动维护索引
i=0forwordinwords:print(i,word)i+=1用 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)ifi>=50:break- 扩展词汇表(重新编号)
all_tokens=sorted(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,start=1):只取值,但记录位置[ifori,vinenumerate(lst)ifv==target]对比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"]result=enumerate(words)print(result)# <enumerate object at 0x...>print(type(result))# <class 'enumerate'>它不是一次性生成所有(index,value)对,而是惰性计算——每次next()才产生下一对,所以省内存。2.内部工作原理# enumerate 的等价实现(简化版)defmy_enumerate(iterable,start=0):count=startforiteminiterable:yield(count,item)count+=1# 因此可以这样拆解:e=enumerate(["a","b","c"])print(next(e))# (0, 'a')print(next(e))# (1, 'b')print(next(e))# (2, 'c')print(list(e))# [] — 迭代器耗尽,后续为空关键理解:enumerate对象是一次性的迭代器。这和列表不同: e=enumerate(["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,v=i_v_tuple# 手动拆包4.start 参数的实际用途# start=1:显示为人类习惯的第 1 行forline_no,textinenumerate(lines,start=1):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 轮: integer=0, token="!" → {"!": 0}# 第 2 轮: integer=1, token='"' → {'"': 1}# 第 3 轮: integer=2, token="'" → {"'": 2}# 第 4 轮: integer=3, token="the" → {"the": 3}# 第 5 轮: integer=4, token="hello" → {"hello": 4}注意字典推导式中 integer 和 token 的位置:值写在前面 token:integer,enumerate产出的 integer 被用作字典的 value。6.常见进阶用法 sentence="I HAD always thought Jack".split()# 同时获取索引、值、值的长度fori,wordinenumerate(sentence):print(i,word,len(word))# 只在特定条件下使用索引target_indices=[ifori,wordinenumerate(sentence)ifword=="Jack"]# [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: 手动计数器 — 啰嗦,容易遗漏 i+=1i=0foriteminseq:print(i,item)i+=1# ✅ 方式3: enumerate — 标准写法fori,iteminenumerate(seq):print(i,item)enumerate的优势: 不需要对象有len()(比如文件对象、生成器) 不需要支持索引[](比如set、dict.keys()) 一行完成,不会忘记 i+=18.常见陷阱# 陷阱1: 在循环中修改列表会导致索引错乱words=["a","b","c"]fori,winenumerate(words):ifw=="b":delwords[i]# ⚠️ 危险!enumerate 不知道列表变了# 建议:遍历副本或收集要删除的索引# 陷阱2: enumerate 不可重复消费e=enumerate([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,start=0)在遍历时同时给你索引和值。在 Ch02 里,它最重要的用途就是把单词列表变成{单词:数字ID}的词汇表字典。