刘心向学(48):zip() —— 并行遍历的艺术

B站影视 电影资讯 2025-10-06 11:03 1

摘要:Increase knowledge, leave a beautiful!

分享兴趣,传播快乐,

增长见闻,留下美好!

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

今天小编为大家带来文章

“刘心向学(48):zip —— 并行遍历的艺术”

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 (48): zip — The Art of Parallel Iteration”

Welcome to your visit.

当你有两个(或多个)列表,并希望“一对一对”地处理它们的元素时,zip 就是为你而生的。

When you have two (or more) lists and want to process their elements pair by pair, zip is the perfect tool.

names = ['Alice', 'Bob']

ages = [25, 30]

for name, age inzip(names, ages):

print(f"{name} is {age} years old")

无需索引,无需 range(len),代码清晰、意图明确。

No indices. No range(len). Just clean, clear code with obvious intent.

*iterables

:一个或多个可迭代对象

: one or more iterable objects

返回一个 zip 对象,它是迭代器,生成元组 (x, y, ...),每个元组包含来自每个可迭代对象的一个元素。

Returns a zip object — an iterator that yields tuples (x, y, ...) where each element comes from one of the inputs.

示例Examplea = [1, 2, 3]b = ['x', 'y', 'z']zipped = zip(a, b)print(list(zipped)) # [(1, 'x'), (2, 'y'), (3, 'z')]解包使用Unpacking in Loopsfor num, letter in zip(a, b):print(num, letter)四、实战应用案例(Practical Use Cases)1. 合并两个列表Merging Two Listskeys = ['name', 'age', 'city']values = ['Alice', 25, 'Beijing']for k, v in zip(keys, values):print(f"{k}: {v}")2. 构建字典Building a Dictionaryperson = dict(zip(keys, values))print(person) # {'name': 'Alice', 'age': 25, 'city': 'Beijing'}Combined with enumeratefori, (name, age) inenumerate(zip(names, ages), 1):print(f"{i}. {name}, {age}years old")4. 转置二维数据(如矩阵)Transposing 2D Data (e.g., Matrix)matrix = [[1, 2, 3],[4, 5, 6]]transposed = list(zip(*matrix))print(transposed) # [(1, 4), (2, 5), (3, 6)]

*matrix 将列表解包为参数:zip([1,2,3], [4,5,6])

*matrix

unpacks the list: zip([1,2,3], [4,5,6])

5. 函数参数解包

Function Argument Unpacking

def greet(name, age):

print(f"Hello {name}, you are {age}")

people = [('Alice', 25), ('Bob', 30)]

for p in people:

greet(*p) # 解包元组作为参数

zip 默认以最短序列为准:

a = [1, 2, 3, 4]

b = ['x', 'y']

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

你可以用 zip(*zipped) 来“解压”:

Use zip(*zipped) to "unzip":

pairs = [(1, 'x'), (2,'y'), (3, 'z')]

nums, letters = zip(*pairs)

print(nums) # (1, 2, 3)print(letters) # ('x', 'y', 'z')

当你希望以最长序列为准,缺失值用默认值填充:

To iterate until the longest sequence ends, filling missing values:

from itertools import zip_longest

a = [1, 2, 3, 4]b = ['x', 'y']for x, y in zip_longest(a, b, fillvalue='N/A'):print(x, y)# 输出:# 1 x# 2 y# 3 N/A# 4 N/Az = zip([1,2], [3,4])print(list(z)) # [(1, 3), (2, 4)]print(list(z)) # —— 已耗尽!如需多次使用,保存为列表:To reuse, convert to list:

z_list = list(zip(a, b))

zip:无参数 → 空迭代器

zip

(no args) → empty iterator

zip(a)

:单个可迭代对象 → 生成单元素元组 (x,)

zip(a)

(single iterable) → yields single-element tuples (x,)list

(zip) # list(zip([1,2])) # [(1,), (2,)]

zip 是 Python 中“组合之美”的体现。

zip

embodies the beauty of composition in Python.

它让并行遍历变得简单、安全、优雅。

It makes parallel iteration simple, safe, and elegant.

它提醒我们:

It reminds us:

“当多个序列需要协同操作时,不要手动管理索引 —— 让 zip 帮你对齐。”

“When multiple sequences need to be processed together — don’t manage indices manually. Let zip align them for you.”

从今天起,当你面对多个列表时,先问自己:

From now on, when you face multiple lists, ask:

“我是不是该用 zip?”

“Should I use zip?”

答案,往往就在其中。

The answer is usually yes.

因为真正的简洁,不是代码少,而是逻辑清晰、意图明确

Because true simplicity isn’t just fewer lines — it’s clear logic and obvious intent.

而 zip,正是通往这种编程境界的又一小步。

And zip is yet another 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学苑

相关推荐