摘要:enumerate(iterable, start=0) 是一个内置函数,它接收一个可迭代对象(如列表、元组、字符串等),并返回一个枚举对象(iterator),每个元素是一个包含 (index, value) 的元组。
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是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”
或者更原始的:
Or even more manually:
这些写法都存在一个问题:手动管理索引。
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(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.
items = ['a', 'b', 'c']for index, value inenumerate(items):print(f"{index}: {value}")# 输出:# 0: a# 1: b# 2: c2. 指定起始索引Custom Start Indexfor 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.
e = enumerate(['x', 'y'])print(next(e)) # (0, 'x')print(next(e)) # (1, 'y')五、实战应用案例(Practical Application Examples)1. 查找元素的所有位置Find All Positions of an Elementdef 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 Menusoptions = ["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. Exit3. 与字符串结合:逐字符处理With Strings: Process Characters with Positiontext = "hello"fori, char inenumerate(text):print(f"Position {i}: '{char}'")# 输出:# Position 0: 'h'# Position 1: 'e'# ...4. 读取文件并打印行号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 Sequencedef find_increasing_start(lst):for i inrange(len(lst) - 1):if lst[i] 六、高级技巧(Advanced Techniques)1. 解包技巧:index, valueUnpacking: index, valuefor i, val inenumerate(data):# 直接使用 i 和 valprocess(i, val)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 Comprehensionsitems = ['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.
enumerate 是 Python 中“小工具,大用途”的典范。它用最简单的方式,解决了“遍历时带索引”这一高频需求。
enumerateis 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.
而 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
来源:LearningYard学苑