news 2026/7/30 23:43:41

enumerate 的用法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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 中的实际用例
你打开的文件中就有大量使用:

  1. 构建词汇表(token → ID 映射)

ch02.ipynb: 把排好序的唯一 token 列表映射为数字

vocab={token:integerforinteger,tokeninenumerate(all_words)}

效果: {“!”: 0, ‘"’: 1, “'”: 2, “(”: 3, …}

  1. 查看词汇表前 51 项
fori,iteminenumerate(vocab.items()):print(item)ifi>=50:break
  1. 扩展词汇表(重新编号)
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()(比如文件对象、生成器) 不需要支持索引[](比如setdict.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}的词汇表字典。
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/30 23:41:45

CocoaPods-Rome:让Xcode外框架构建变得前所未有的简单

CocoaPods-Rome&#xff1a;让Xcode外框架构建变得前所未有的简单 【免费下载链接】Rome Makes it easy to build a list of frameworks. 项目地址: https://gitcode.com/gh_mirrors/rome1/Rome CocoaPods-Rome是一款强大的CocoaPods插件&#xff0c;它能让开发者轻松构…

作者头像 李华
网站建设 2026/7/30 23:41:36

CPSW以太网交换机网络统计机制:从硬件计数器到网络诊断实战

1. CPSW以太网交换机网络统计机制深度解析在嵌入式网络系统开发中&#xff0c;尤其是在工业控制、汽车电子或通信设备这类对实时性与可靠性要求极高的领域&#xff0c;网络交换机的“黑盒”状态是工程师最头疼的问题之一。数据包为什么延迟了&#xff1f;网络为何突然拥堵&…

作者头像 李华
网站建设 2026/7/30 23:40:20

运维实战分享|富士通 Fujitsu 服务器 ESXi 8 全套原厂 OEM 资源实操指南

最近不少同行私信咨询富士通服务器部署 ESXi 的相关问题&#xff0c;很多人反馈通用公版镜像装完问题一大堆&#xff1a;RAID 阵列识别空白、板载网卡无驱动、iRMC 远程管理完全失联&#xff0c;硬件温度、风扇转速这类监控数据全部读取失败。 我也从事过企业机房虚拟化运维一段…

作者头像 李华
网站建设 2026/7/30 23:39:02

CocoaPods-Rome源码解析:探索框架自动构建的实现原理

CocoaPods-Rome源码解析&#xff1a;探索框架自动构建的实现原理 【免费下载链接】Rome Makes it easy to build a list of frameworks. 项目地址: https://gitcode.com/gh_mirrors/rome1/Rome CocoaPods-Rome是一款专为iOS开发者打造的高效框架自动构建工具&#xff0c…

作者头像 李华
网站建设 2026/7/30 23:38:27

笔记十三:PPO(近端策略优化)从零到一完全指南(终极干净版)

适用场景:强化学习入门、LLM(大语言模型)RLHF 微调基础、面试复习、代码落地参考。 阅读对象:假设读者完全不懂强化学习,从零开始,用大白话逐步深入到数学公式和工程细节。 目录 PPO 是干什么的?—— 动机与历史 PPO 的核心思想与数学公式 PPO 裁剪 vs 学习率 vs 梯度裁…

作者头像 李华