Python 的 zip() 函数


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.

我们来看一下一个简单的示例,了解其工作原理?

示例

 在线演示

## initializing two lists
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## zipping both
## zip() will return pairs of tuples with corresponding elements from both lists
print(list(zip(names, ages)))

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

输出

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

我们还可以从压缩对象中解压元素。我们必须传递一个对象并用一个前导 * 传递给 zip() 函数。我们来看一下。

示例

 在线演示

## initializing two lists
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## zipping both
## zip() will return pairs of tuples with corresponding elements from both lists
zipped = list(zip(names, ages))
## unzipping
new_names, new_ages = zip(*zipped)
## checking new names and ages
print(new_names)
print(new_ages)

如果您运行以上程序,您会获得以下结果。

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

zip() 的一般用途

我们可以使用它来同时打印来自不同迭代器的多个对应元素。我们来看一下以下示例。

示例

 在线演示

## initializing two lists
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## printing names and ages correspondingly using 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

更新日期:2019 年 7 月 30 日

417 次浏览

职业马上开启

完成课程获得认证

开始
广告
© . All rights reserved.