刘心向学(47):enumerate() —— 优雅地遍历索引与元素

刘心向学(47):enumerate() —— 优雅地遍历索引与元素

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是LearningYard新学苑。

今天小编为大家带来文章

“刘心向学(47):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 (47): enumerate() — Iterate with Index and Value, the Pythonic Way

Have you written code like this?”

Welcome to your visit.

一、思维导图(Mind Map)

刘心向学(47):enumerate() —— 优雅地遍历索引与元素


二、引言(Introduction)

在编程中,我们常常需要“一边遍历,一边知道位置”。

传统方式:

In programming, we often need to “loop over items and know their position.”

The traditional way:

for i in range(len(data)):print(i, data[i])

问题:

Problems:

冗长

Verbose

易出错(如索引越界)

Error-prone (e.g., index out of bounds)

可读性差

Harder to read

而 enumerate() 的出现,正是为了解决这个问题:

enumerate() was designed to solve this:

for i, item in enumerate(items):

print (i, item)

简洁、清晰、安全。

Clean. Clear. Safe.


三、基本语法(Basic Syntax)enumerate (iterable, start=0)

iterable

:可迭代对象(列表、元组、字符串等)

iterable

: any iterable (list, tuple, string, etc.)start

:起始索引,默认为 0

start: starting index (default: 0)返回值

Return Value

返回一个 enumerate 对象,它是一个迭代器,生成 (index, value) 元组。

Returns an enumerate object — an iterator that yields (index, value) tuples.

items = ['a', 'b', 'c']

enum = enumerate(items)
print(list(enum))  # [(0, 'a'), (1, 'b'), (2, 'c')]

解包使用(最常见)

Unpacking (Most Common)

for index, value in enumerate (items):

print(f"{index}{value}")

四、实战应用案例(Practical Use Cases)

1. 带序号的打印

Numbered Printing

fruits = ['apple', 'banana', 'cherry']

for i, fruit inenumerate(fruits, start=1):
print(f"{i}{fruit}")
# 输出:
# 1. apple
# 2. banana
# 3. cherry

2. 查找满足条件的索引

Find Indices by Condition

words = [“hello”, “world”, “python”]

for i, word inenumerate(words):
if"o"in word:
print(f"Found 'o' at index {i}{word}")

3. 构建元素到索引的映射

Build Value-to-Index Mapping

items = ['foo', 'bar', 'baz']

index_map = {item: i for i, item inenumerate(items)}
print(index_map)  # {'foo': 0, 'bar': 1, 'baz': 2}

4. 与列表推导式结合

With List Comprehensions

data = [10, 20, 30]

result = [f"{i}:{x}"for i, x inenumerate(data)]
print(result)  # ['0:10', '1:20', '2:30']

5. 避免多重 enumerate误区

Avoid Nested enumeratePitfalls

错误:嵌套 enumerate 不会自动对齐

Wrong: Nested enumerate doesn’t align automatically

a = [1, 2, 3]

b = ['x''y''z']
for i, x inenumerate(a):
for j, y inenumerate(b):
if i == j:
print(x, y)  # 可读性差

正确:使用 zip()for

Correct: Use zip()

x, y inzip(a, b):

print(x, y)

或带索引的 zip:

Or with index:

for i, (x, y) in enumerate(zip(a, b)):

print(i, x, y)

五、高级技巧(Advanced Tips)

1. 自定义起始索引

Custom Start Index

for i, line in enumerate(log_lines, start=1):

print(f”[Line {i}] {line}”)

超级适合日志、文件行号等场景。

Perfect for logs, file lines, etc.

2. 与 zip()结合

Combined with zip()

names = ['Alice', 'Bob']

ages = [25, 30]

fori, (name, age) inenumerate(zip(names, ages), 1):

print(f”{i}. {name}is {age}years old”)


六、注意事项(Caveats)

1. enumerate是迭代器

enumerateis an Iterator

enum = enumerate(['a', 'b'])

print(list(enum))  # [(0, 'a'), (1, 'b')]
print(list(enum))  # [] —— 已耗尽!

如需多次使用,转换为列表:

If you need to reuse it, convert to list:

enum_list = list(enumerate(items))

2. 何时不适用?(When Not to Use?)

仅需元素:直接 for item in items

Only need values: use for item in items

仅需索引:for i in range(n)

Only need indices: use for i in range(n)

需要复杂索引逻辑:仍可用 range(len())

Complex indexing logic: range(len()) may still apply

绝大多数“索引+元素”场景,enumerate() 都是首选

But for most “index + value” cases, enumerate() is the best choice.


七、结语(Conclusion)

enumerate() 是 Python 中“小而美”的典范。

enumerate()

is a small but beautiful feature in Python.

它不复杂,却极大提升了代码的可读性安全性

It’s simple, yet greatly improves code readability and safety.

它提醒我们:

It reminds us:

“不要自己造轮子,善用内置工具。”

“Don’t reinvent the wheel — use built-in tools.”

从今天起,当你写下:

From now on, whenever you write:

for i in range(len(data)):

请停下来,问自己:

Pause and ask:

“我是不是该用 enumerate()?”

“Should I use enumerate() instead?”

大致率,答案是肯定的。

Chances are, the answer is yes.

由于真正的 Pythonic 代码,不是“能运行”,而是“清晰、简洁、优雅”。

Because truly Pythonic code isn’t just “working” — it’s clear, concise, and elegant.

而 enumerate(),正是通往这种境界的一小步。

And enumerate() is a small step toward that ideal.


今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,

让我们相约明天。

祝您今天过得开心快乐!

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

审核|hzy

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
芳华绝代的头像 - 鹿快
评论 抢沙发

请登录后发表评论

    暂无评论内容