Python zip() 函数

pythonserver side programmingprogramming更新于 2025/7/16 0:12:17

zip() 函数用于对多个迭代器进行分组。使用 help 方法查看 zip() 函数的文档。运行以下代码以获取有关 zip() 函数的帮助。

示例

help(zip)

如果你运行上述程序,你将得到以下结果。

输出

Help on class zip in module builtins:
class zip(object)
   | zip(iter1 [,iter2 [...]]) --> zip object
   |
   | Return a zip object whose .__next__() method returns a tuple where
   | the i-th element comes from the i-th iterable argument. The .__next__()
   | method continues until the shortest iterable in the argument sequence
   | is exhausted and then it raises StopIteration.
   |
   | Methods defined here:
   |
   | __getattribute__(self, name, /)
   | Return getattr(self, name).
   |
   | __iter__(self, /)
   | Implement iter(self).
   |
   | __new__(*args, **kwargs) from builtins.type
   | Create and return a new object. See help(type) for accurate signature.
   |
   | __next__(self, /)
   | Implement next(self).
   |
   | __reduce__(...)
   | Return state information for pickling.

让我们看一个简单的例子来了解它是如何工作的?

示例

## 初始化两个列表
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## 压缩两者
## zip() 将返回两个列表中具有相应元素的元组对
print(list(zip(names, ages)))

如果运行上述程序,您将获得以下结果

输出

[('Harry', 19), ('Emma', 20), ('John', 18)]

我们还可以从压缩的对象中解压缩元素。我们必须将带有前导 * 的对象传递给 zip() 函数。让我们看看。

示例

## 初始化两个列表
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## 压缩两者
## zip() 将返回两个列表中具有相应元素的元组对
zipped = list(zip(names, ages))
## 解压缩
new_names, new_ages = zip(*zipped)
## 检查新名称和年龄
print(new_names)
print(new_ages)

如果你运行上述程序,你将得到以下结果。

('Harry', 'Emma', 'John')
(19, 20, 18)

zip() 的一般用法

我们可以使用它一次打印来自不同迭代器的多个相应元素。让我们看看下面的例子。

示例

## 初始化两个列表
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## 使用 zip() 分别打印姓名和年龄
for name, age in zip(names, ages):
print(f"{name}'s age is {age}")

如果你运行上述程序,你将得到以下结果。

输出

Harry's age is 19
Emma's age is 20
John's age is 18

相关文章


有用资源