python的zip()函数

zip() 函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象。

如果各个可迭代对象的元素个数不一致,则返回的对象长度与最短的可迭代对象相同。

利用 * 号操作符,与zip相反,进行解压。

zip() 函数语法:

1
zip (iterable1,iterable2, ...)

参数说明:

  • iterable -- 一个或多个可迭代对象(字符串、列表、元祖、字典)

Python2中:

1
2
3
4
5
6
7
8
9
10
>>>a  =  [1,2,3] #此处可迭代对象为列表
>>> b  =  [4,5,6]
>>> c  =  [4,5,6,7,8]
>>> zipped  =  zip(a,b)     # 打包为元组的列表
>>> zipped
[( 1 ,  4 ), ( 2 ,  5 ), ( 3 ,  6 )]
>>>  zip (a,c)               # 元素个数与最短的列表一致
[( 1 ,  4 ), ( 2 ,  5 ), ( 3 ,  6 )]
>>>  zip ( * zipped)           # 与 zip 相反,可理解为解压
[( 1 ,  2 ,  3 ), ( 4 ,  5 ,  6 )]

Python3中:

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> a  =  [1,2,3] #此处可迭代对象为列表
>>> b  =  [4,5,6]
>>> c  =  [4,5,6,7,8]
>>> zipped  =  zip(a,b)
>>> zipped
< zip  object at 0x02B01B48> #返回的是一个对象
>>>  list (zipped)
[( 1 ,  4 ), ( 2 ,  5 ), ( 3 ,  6 )]  #使用list()函数转换为列表
>>>  list ( zip (a,c))
[( 1 ,  4 ), ( 2 ,  5 ), ( 3 ,  6 )]
>>> zipped  =  zip(a,b)
>>>  list ( zip ( * zipped))  #解压也使用list进行转换
[( 1 ,  2 ,  3 ), ( 4 ,  5 ,  6 )]

搭配for循环支持并行迭代:

1
2
3
4
5
6
7
#!/usr/bin/python3
 
list1  =  [2,3,4]
list2  =  [4,5,6]
 
for  x,y in zip(list1,list2):
     print (x,y, '--' ,x * y)

结果:

1
2
3
2  4 -- 8
3  5 -- 15
4  6 -- 24

来源:https://www.cnblogs.com/wushuaishuai/p/7766470.html

猜你喜欢

转载自www.cnblogs.com/yibeimingyue/p/11275580.html