网站首页 > 技术文章 正文
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来文章
“刘心向学(44):enumerate()—— 拒绝手动计数,让循环自带索引”
Share interest, spread happiness,
Increase knowledge, leave a beautiful!
Dear, this is LearningYard Academy.
Today, the editor brings you an article.
“Liu Xin Xiang Xue (44): enumerate() — Stop Manual Counting, Let Loops Carry Their Own Index”
Welcome to your visit.
一、思维导图(Mind Map)
二、引言(Introduction)
你一定写过这样的代码:
You’ve likely written code like this:
for i in range ( len (items)):
print(f"{i}: {items[i]}")
或者更原始的:
Or even more manually:
i = 0for x in items:
print(f"{i}: {x}")
i += 1
这些写法都存在一个问题:手动管理索引。
These approaches share a common flaw: manually managing the index.
容易出错(比如索引越界)
Prone to errors (e.g., off-by-one, index out of bounds)
代码冗长
Verbose and hard to read
不够 Pythonic
Not Pythonic
而 Python 的哲学是:
But Python’s philosophy says:
“There should be one obvious way to do it.”
“Simple is better than complex.”
enumerate() 就是那个“明显的方式”。
enumerate() is that obvious, simple way.
三、什么是 enumerate()?(What is enumerate()?)
enumerate(iterable, start=0) 是一个内置函数,它接收一个可迭代对象(如列表、元组、字符串等),并返回一个枚举对象(iterator),每个元素是一个包含 (index, value) 的元组。
enumerate(iterable, start=0)
is a built-in function that takes an iterable (like a list, tuple, or string) and returns an iterator of tuples, where each tuple is (index, value).
一句话:
In short:
enumerate() 让你在遍历时自动获得索引,无需手动计数。
enumerate() gives you the index automatically during iteration — no manual counting needed.
四、基本用法(Basic Usage)
1. 默认从 0 开始
Default Start at 0
items = ['a', 'b', 'c']
for index, value inenumerate(items):
print(f"{index}: {value}")
# 输出:
# 0: a
# 1: b
# 2: c
2. 指定起始索引
Custom Start Index
for index, value in enumerate (items, start=1):print(f"{index}: {value}")# 输出:# 1: a# 2: b# 3: c
常用于生成从 1 开始的序号,如菜单、排行榜等。
Commonly used for 1-based numbering, such as menus, leaderboards, etc.
3. enumerate 返回的是迭代器
3. enumerate()Returns an Iterator
e = enumerate(['x', 'y'])
print(next(e)) # (0, 'x')
print(next(e)) # (1, 'y')
五、实战应用案例(Practical Application Examples)
1. 查找元素的所有位置
Find All Positions of an Element
def find_all_positions(lst, target):return[i fori, x inenumerate(lst) ifx == target]numbers = [1, 2, 3, 2, 4, 2]positions = find_all_positions(numbers, 2)print(positions) # [1, 3, 5]
2. 生成带序号的菜单
Generate Numbered Menus
options = ["New Game", "Load Game", "Settings", "Exit"]
print("Main Menu:")
for i, option inenumerate(options, start=1):
print(f" {i}. {option}")
# 输出:
# Main Menu:
# 1. New Game
# 2. Load Game
# 3. Settings
# 4. Exit
3. 与字符串结合:逐字符处理
With Strings: Process Characters with Position
text = "hello"fori, char inenumerate(text):print(f"Position {i}: '{char}'")# 输出:# Position 0: 'h'# Position 1: 'e'# ...
4. 读取文件并打印行号
Read File with Line Numbers
with open('data.txt') as f:
for line_num, line inenumerate(f, start=1):
print(f"{line_num}: {line.rstrip()}")
5. 算法题:找出递增序列的起始索引
Algorithm: Find Start of Increasing Sequence
def find_increasing_start(lst):for i inrange(len(lst) - 1):
if lst[i] < lst[i + 1]:
return i
return -1
# 使用 enumerate 更清晰
deffind_increasing_start_v2(lst):
for i, (curr, next_val) inenumerate(zip(lst, lst[1:])):
if curr < next_val:
return i
return -1
六、高级技巧(Advanced Techniques)
1. 解包技巧:index, value
Unpacking: index, value
for i, val inenumerate(data):# 直接使用 i 和 valprocess(i, val)
2. 与 zip()结合
Combine with zip()
names = ['Alice', 'Bob', 'Charlie']scores = [85, 92, 78]fori, (name, score) inenumerate(zip(names, scores), start=1):print(f"{i}. {name}: {score}分")
3. 在列表推导式中使用
In List Comprehensions
items = ['a', 'b', 'c']result = [f"{i}:{x}"fori, x inenumerate(items)]print(result) # ['0:a', '1:b', '2:c']
七、注意事项(Important Notes)
enumerate() 返回的是迭代器,不是列表
enumerate() returns an iterator, not a list
它是惰性求值的,节省内存。如需多次使用,可转换为列表:
t’s lazy-evaluated, memory-efficient. If you need multiple passes, convert it:
list (enumerate(items))
不支持直接索引访问
Does not support direct indexing
不能写 enumerate(items)[0],会报错。如需随机访问,先转为列表。
You can’t write enumerate(items)[0] — it will raise an error. Convert to list first for random access.
不要在循环中修改原列表
虽然 enumerate 本身不会阻止你修改列表,但可能导致逻辑混乱或跳过元素。
Avoid modifying the original list during iteration
While enumerate won’t stop you, modifying the list can lead to logic errors or skipped elements.
八、结语(Conclusion)
enumerate() 是 Python 中“小工具,大用途”的典范。它用最简单的方式,解决了“遍历时带索引”这一高频需求。
enumerate()is a classic example of a small tool with big impact in Python. It solves a common problem — accessing index during iteration — in the simplest, most elegant way.
它不仅让代码更简洁,更重要的是:
It does more than just shorten code. It:
减少了手动计数的错误
Reduces errors from manual counting
提升了代码的可读性和可维护性
Improves readability and maintainability
体现了 Python 的“优雅”哲学
Embodies Python’s philosophy of elegance
正如 Python 之禅所说:
As stated in the Zen of Python:
“Beautiful is better than ugly.”
“Explicit is better than implicit.”
而 for i, x in enumerate(...),正是这种美学的完美体现。
And for i, x in enumerate(...) is a perfect embodiment of that beauty.
下次当你想写 range(len(...)) 时,请记住:
Next time you reach for range(len(...)), remember:
“There’s a better way.”
那就是 enumerate()。
That way is enumerate().
今天的分享就到这里了。
如果您对文章有独特的想法,
欢迎给我们留言,
让我们相约明天。
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
参考资料:通义千问
参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.
Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.
本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!
LearningYard新学苑
文字:song
排版:song
审核|qiu
猜你喜欢
- 2025-09-21 layui table单元格高度自适应造成固定的表格列样式错乱
- 2025-09-21 50个常用 jQuery使用技巧整理汇总
- 2025-09-21 用TensorFlow基于神经网络实现井字棋(含代码)
- 2025-09-21 终于有人把排序算法讲明白了_排序算法 菜鸟教程
- 2025-09-21 When DeepSeek is Your Stock Advisor
- 2024-08-05 有了 for 循环 为什么还要 forEach?
- 2024-08-05 20220814项目管理周贴士(《项目管理》)
- 2024-08-05 我爱Julia之入门-067(数组27)
- 2024-08-05 用excel作画的老爷子火了,但是如何统计单元格填充色你知道吗?
- 2024-08-05 鸿蒙开发中LazyForEach的使用(鸿蒙开发视频教程)
- 最近发表
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)