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

B站影视 韩国电影 2025-09-29 16:08 1

摘要:Increase knowledge, leave a beautiful!

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是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.

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

传统方式:

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

返回一个 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')]

for index, value in enumerate (items):

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

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

words = ["hello", "world", "python"]

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

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

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

data = [10, 20, 30]

result = [f"{i}:{x}"for i, x inenumerate(data)]print(result) # ['0:10', '1:20', '2:30']b = ['x', 'y', 'z']for i, x inenumerate(a):for j, y inenumerate(b):if i == j:print(x, y) # 可读性差

正确:使用 zipfor

或带索引的 zip:

Or with index:

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

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

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

非常适合日志、文件行号等场景。

Perfect for logs, file lines, etc.

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")

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))

仅需元素:直接 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.

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

来源:LearningYard学苑

相关推荐