苦练Python第31天:enumerate、zip与元组解包

201 阅读2分钟

前言

大家好,我是倔强青铜三。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎回到 苦练Python100天 的第 31 天!
今天,我们一口气掌握三个常被忽视、却能瞬间让代码 更简洁、更优雅、更具表达力 的 Python 神技:

  • enumerate()
  • zip()
  • 元组解包

下面用极简示例带你秒懂。


🔢 1. enumerate() —— 循环里同时拿索引和值

❌ 传统写法

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

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

✅ 优雅写法

for index, fruit in enumerate(fruits):
    print(index, fruit)

输出:

0 apple
1 banana
2 cherry

想让索引从 1 开始?

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)

🔗 2. zip() —— 多列表元素配对神器

✅ 基本用法

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")

输出:

Alice scored 85
Bob scored 92
Charlie scored 78

⚠️ 长度不一致?

zip() 会停在最短的序列:

a = [1, 2, 3]
b = ['x', 'y']
print(list(zip(a, b)))  # [(1, 'x'), (2, 'y')]

需要填充缺失值,请用 itertools.zip_longest()


🎁 3. 解包 —— 把序列一键拆成变量

✅ 元组解包

person = ("John", 25, "Engineer")
name, age, job = person

print(name)  # John
print(age)   # 25
print(job)   # Engineer

✅ 循环里直接拆

pairs = [(1, 'one'), (2, 'two'), (3, 'three')]

for number, word in pairs:
    print(f"{number} = {word}")

🎯 忽略不需要的值

data = ("Tom", 30, "Doctor")
name, _, profession = data

下划线 _ 是约定俗成的“占位符”。


🔍 为什么值得用?

工具典型场景
enumerate()需要索引 + 值的循环
zip()并行迭代多个序列
解包简洁地把序列拆成变量

三者结合,让你的代码 更易读、更 Pythonic、更少 Bug


🧠 实战挑战

students = ['Emma', 'Liam', 'Olivia']
grades = [91, 88, 95]

# 任务:输出 "1. Emma scored 91" 等
# 提示:同时用 enumerate() 和 zip()

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!