本文实例讲述了Python zip()函数用法。分享给大家供大家参考,具体如下:
这里介绍python中zip()函数的使用:
1
2
3
4
|
>>> help ( zip ) Help on built - in function zip in module __builtin__: zip (...) zip (seq1 [, seq2 [...]]) - > [(seq1[ 0 ], seq2[ 0 ] ...), (...)] |
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
zip([seq1, ...])
接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。若传入参数的长度不等,则返回列表的长度和参数中长度最短的对象相同。
1》
1
2
3
4
5
|
>>> x = [ 1 , 2 , 3 ] >>> y = [ 1 , 2 , 3 ] >>> z = ( 1 , 2 , 3 ) >>> zip (x,y,z) [( 1 , 1 , 1 ), ( 2 , 2 , 2 ), ( 3 , 3 , 3 )] |
2》
1
2
3
4
|
>>> x = ( 1 , 2 , 3 , 4 ) >>> y = [ 1 , 2 , 3 ] >>> zip (x,y) #传入参数的长度不等,则返回列表的长度和参数中长度最短的对象相同 [( 1 , 1 ), ( 2 , 2 ), ( 3 , 3 )] |
3》
1
2
3
4
|
>>> x ( 1 , 2 , 3 , 4 ) >>> zip (x) [( 1 ,), ( 2 ,), ( 3 ,), ( 4 ,)] |
4》
1
2
|
>>> zip () [] |
5》zip()配合*号操作符,可以将已经zip过的列表对象解压
1
2
3
4
5
6
7
8
|
>>> x = [ 1 , 2 , 3 ] >>> y = [ 'a' , 'b' , 'c' ] >>> z = [ 4 , 5 , 6 ] >>> xyz = zip (x,y,z) >>> xyz [( 1 , 'a' , 4 ), ( 2 , 'b' , 5 ), ( 3 , 'c' , 6 )] >>> zip ( * xyz) [( 1 , 2 , 3 ), ( 'a' , 'b' , 'c' ), ( 4 , 5 , 6 )] |
6》
1
2
3
4
5
6
7
8
9
|
>>> x = [ 5 , 6 , 7 ] >>> [x] #[x]生成一个列表的列表,它只有一个元素x [[ 5 , 6 , 7 ]] >>> [x] * 3 #[x] * 3生成一个列表的列表,它有3个元素,[x, x, x] [[ 5 , 6 , 7 ], [ 5 , 6 , 7 ], [ 5 , 6 , 7 ]] >>> x [ 5 , 6 , 7 ] >>> zip ( * [x] * 3 ) #zip(* [x] * 3)等价于zip(x, x, x) [( 5 , 5 , 5 ), ( 6 , 6 , 6 ), ( 7 , 7 , 7 )] |
7》
1
2
3
4
5
6
7
8
9
10
|
>>> name = [ 'song' , 'ping' , 'python' ] >>> age = [ 26 , 26 , 27 ] >>> zip (name,age) [( 'song' , 26 ), ( 'ping' , 26 ), ( 'python' , 27 )] >>> for n,a in zip (name,age): ... print n,a ... song 26 ping 26 python 27 |
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/sxingming/article/details/51476540