当前位置: 首页 > news >正文

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}的词汇表字典。
http://www.cnnetsun.cn/news/3757075.html

相关文章:

  • CocoaPods-Rome:让Xcode外框架构建变得前所未有的简单
  • CPSW以太网交换机网络统计机制:从硬件计数器到网络诊断实战
  • 如何让PDF文档在小屏幕上获得最佳阅读体验?Briss 2.0的智能裁剪解决方案
  • 运维实战分享|富士通 Fujitsu 服务器 ESXi 8 全套原厂 OEM 资源实操指南
  • CocoaPods-Rome源码解析:探索框架自动构建的实现原理
  • 笔记十三:PPO(近端策略优化)从零到一完全指南(终极干净版)
  • C++实现气候突变检测:滑动T检验与MK检验算法详解与工程实践
  • 【限时开源】2024最新AI蒸馏评估框架发布:覆盖17个SOTA模型、9类硬件平台、5维量化指标(含延迟/功耗/精度三维帕累托前沿分析)
  • 2026年英语教学工具深度测评:5款主流方案实测对比与选型指南
  • Beyond Compare 5密钥生成器:从逆向工程到一键激活的完整解决方案
  • KRAS[G12D]突变体的生物学特性与靶向治疗进展
  • VengeanceUI未来路线图:即将发布的5个令人期待的新功能预览
  • 大语言模型编程实战:从入门到工程化应用
  • 现在的 cursor 或者agent 系统怎么实现执行python代码的,怎么执行cli命令的,需要什么环境
  • 深度解析:Windows平台微信QQ防撤回补丁的技术实现原理
  • 探索Aidoku:您专属的iOS漫画阅读神器如何实现无广告沉浸体验?
  • 后端开发者转型大模型应用开发的实战指南
  • 同样是SMT贴片,为什么车载PCBA代工门槛高?认准这5项资质和设备标准
  • Python pandas高效处理CSV数据实战指南
  • 西门子PLC S7协议TCP通信实战:第三方上位机数据采集避坑指南
  • ChatGPT自动化处理工作琐事的实践指南
  • acts_as_commentable性能优化:10万级评论数据的查询优化技巧
  • Groq Code CLI调试技巧:使用--debug模式解决常见问题
  • 如何解锁中兴光猫的工厂模式?zteOnu工具5步完全指南
  • Loop Engineering 实战:用 opencode-loop 搭一个能自我修正的 AI 开发循环
  • AI数字人软件推荐参考:先按内容目标划分平台类型
  • 国内AI数字人工具免费版与商用版对比:功能权益和使用边界
  • 商业会所锦鲤池自动排污配置,这样搞再也不用自己动手
  • AI语音情绪失控事故复盘(2023-2024行业TOP5失败案例深度解剖)
  • Navicat无限试用终极指南:3种方法轻松重置14天限制