Python zip()函数
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
热门推荐
10 小寒健康祝福语大全简短
11 生日祝福语简短蛋糕上
12 新年给父亲简短祝福语
13 美国护士毕业祝福语简短
14 送红包祝福语简短朋友
15 春节期间祝福语大全简短
16 家人毕业祝福语简短励志
17 新年祝福语简短的个性
18 好姐妹生日祝福语 简短