Python3-zip函数

本文介绍python中zip( )函数的使用:

>>> 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》
>>> 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》
>>> x=(1,2,3,4)
>>> y=[1,2,3]
>>> zip(x,y) #传入参数的长度不等,则返回列表的长度和参数中长度最短的对象相同
[(1, 1), (2, 2), (3, 3)]
3》
>>> x
(1, 2, 3, 4)
>>> zip(x)
[(1,), (2,), (3,), (4,)]
4》
>>> zip()
[]

5》zip()配合*号操作符,可以将已经zip过的列表对象解压
>>> 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》
>>> 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》

>>> 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

猜你喜欢

转载自blog.csdn.net/zbrj12345/article/details/80372954