恒美微站 Logo 恒美微站
  • 首页
  • 关于我们
  • 建站服务
  • 主题模板
  • 案例展示
  • 资讯中心
  • 联系我们

enumerate 的用法

  • 首页
  • 资讯中心
  • /
  • enumerate 的用法

相关资讯

Excel VBA调试技巧:解决宏被禁用、公式不更新等15个常见问题 2026/7/30 23:44:13
从0到1开发InboxLayout:Android仿Google Inbox交互的实战指南 2026/7/30 23:39:12
CocoaPods-Rome源码解析:探索框架自动构建的实现原理 2026/7/30 23:39:12

最新资讯

2026年横评10款降AIGC平台:只选真正管用的那一款!
如何快速修复B站缓存视频:5分钟实现m4s到MP4的无损转换指南
5分钟实现网站永久保存:WebSite-Downloader完整离线下载指南
如何免费解锁Wand专业版功能:3步完成游戏修改体验升级
3分钟掌握百度网盘提取码智能查询:告别资源获取困境的终极方案
GDScript零基础学习终极指南:30天从编程小白到游戏开发者

今日推荐

从零开始的YOLO目标检测全流程:数据标注→模型训练→推理验证→结果可视化
为什么你的BERT微调总掉点?揭秘隐藏在PyTorch DataLoader里的3个数据泄露陷阱,上线前必须检查!
Ryujinx终极指南:免费在电脑上畅玩Switch游戏的完整教程

本周热门

G-Helper完整指南:免费开源工具彻底优化华硕笔记本性能
解决全部报错!OpenClaw Windows适配优化+网关修复教程
覆盖国产 + 海外 + 开源模型,OpenClaw 2.7.9 Windows/Mac 双端部署详解

本月精选

enumerate 的用法

发布时间:2026/7/30 23:44:13
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}的词汇表字典。

关于恒美微站

恒美微站专注于为个体商户、工作室提供极简自助建站服务,让每个人都能轻松拥有专业网站。

快速链接

  • 关于我们
  • 建站服务
  • 主题模板
  • 案例展示
  • 资讯中心

服务项目

  • 可视化建站
  • 拖拽编辑
  • 主题定制
  • SEO 优化
  • 网站托管

联系方式

  • 📍 地址:北京市朝阳区建国路 88 号
  • 📞 电话:400-888-8888
  • ✉️ 邮箱:info@hmyw.cn
  • 🕐 时间:周一至周日 9:00-18:00

© 2024 恒美微站 hmyw.cn 版权所有 | 京 ICP 备 12345678 号