Python zip()函数
在本教程中,我们将学习Python zip函数。
Python zip
如果您是普通计算机用户,则应该使用.zip文件扩展名。
你知道这是什么吗?基本上,.zip本身就是一个容器。
它其中保存真实文件。
同样,Python zip是一个其中保存真实数据的容器。
Python zip函数将可迭代元素作为输入,并返回迭代器。
如果Python zip函数没有可迭代的元素,则它将返回一个空的迭代器。
Python zip函数示例
让我们看一个简单的python zip函数示例。
在上一节中,我们介绍了Python zip所采用的参数及其返回值。
因此,通过不传递任何参数,zip将返回一个空的迭代器。
但是,如果我们传递两个相同长度的可迭代对象,则将返回一个可迭代的python元组,其中该元组的每个元素都将来自这些可迭代列表。
Python zip函数主要用于将两个可迭代元素的数据组合在一起。
请参阅以下代码。
test = zip() # referring a zip class print('The type of an empty zip : ', type(test)) list1 = ['Alpha', 'Beta', 'Gamma', 'Sigma'] list2 = ['one', 'two', 'three', 'six'] test = zip(list1, list2) # zip the values print('\nPrinting the values of zip') for values in test: print(values) # print each tuples
因此,上述python zip示例程序的输出为:
The type of an empty zip : <class 'zip'> Print the values of zip ('Alpha', 'one') ('Beta', 'two') ('Gamma', 'three') ('Sigma', 'six')
注意python类型函数调用的输出,因此zip函数返回zip python类的实例。
具有不同长度的可迭代元素的Python zip示例
现在,如果我们尝试压缩两个或者多个可迭代元素,将会发生什么?好吧,在这种情况下,Python zip函数将添加项,直到给定可迭代元素的项的最低索引为止。
这意味着元组的数量将与给定可迭代元素的最小长度相同。
以下示例将帮助您理解这一点。
# list of 4 elements list1 = ['Alpha', 'Beta', 'Gamma', 'Sigma'] # list of 5 elements list2 = ['one', 'two', 'three', 'six', 'five'] # list of 3 elments list3 = [1, 2, 3] test = zip(list1, list2, list3) # zip the values cnt = 0 print('\nPrinting the values of zip') for values in test: print(values) # print each tuples cnt+=1 print('Zip file contains ', cnt, 'elements.');
因此,此代码的输出将是
Printing the values of zip ('Alpha', 'one', 1) ('Beta', 'two', 2) ('Gamma', 'three', 3) Zip file contains 3 elements.
Python解压缩zip
我们还可以从Python zip函数提取数据。
要提取zip,我们必须使用相同的zip()函数。
但是我们在从压缩变量获得的列表的前面添加了一个星号(*)。
您可以使用list()函数从压缩变量中获取列表。
但是,这将返回多个元组。
该数字将根据zip函数压缩数据所使用的参数数量而有所不同。
请参阅以下代码以了解。
list1 = ['Alpha', 'Beta', 'Gamma', 'Sigma'] list2 = ['one', 'two', 'three', 'six'] test = zip(list1, list2) # zip the values testList = list(test) a, b = zip( *testList ) print('The first list was ', list(a)); print('The second list was ', list(b));
请注意,如果初始列表的长度不同,那么您将不会获得原始列表。
例如,如果上述程序中的list2 = ['one','two','three']
,则输出将如下所示。
The first list was ['Alpha', 'Beta', 'Gamma'] The second list was ['one', 'two', 'three']