zip()函数用于对多个迭代器进行分组。使用帮助方法查看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