python的zip函数

zip()函数

它是Python的内建函数,(与序列有关的内建函数有:sorted()、reversed()、enumerate()、zip()),其中sorted()和zip()返回一个序列(列表)对象,reversed()、enumerate()返回一个迭代器(类似序列)

复制代码
1 >>> type(sorted(s))
2 <type 'list'>
3 >>> type(zip(s))
4 <type 'list'>
5 >>> type(reversed(s))
6 <type 'listreverseiterator'>
7 >>> type(enumerate(s))
8 <type 'enumerate'>
复制代码

那么什么是zip()函数 呢?

我们help(zip)看看:

复制代码
1 >>> help(zip)
2 Help on built-in function zip in module __builtin__:
3 
4 zip(...)
5     zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
6     
7     Return a list of tuples, where each tuple contains the i-th element
8     from each of the argument sequences.  The returned list is truncated
9     in length to the length of the shortest argument sequence.
复制代码

提示:不懂的一定多help

定义:zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。

复制代码
 1 >>> z1=[1,2,3]
 2 >>> z2=[4,5,6]
 3 >>> result=zip(z1,z2)
 4 >>> result
 5 [(1, 4), (2, 5), (3, 6)]
 6 >>> z3=[4,5,6,7]
 7 >>> result=zip(z1,z3)
 8 >>> result
 9 [(1, 4), (2, 5), (3, 6)]
10 >>> 

posted on 2017-02-11 21:35  吃咯  阅读(700)  评论(0编辑  收藏  举报

导航