天天看点

[357]python zip()方法

>>> name=('jack','beginman','sony','pcky')
>>> age=(2001,2003,2005,2000)
>>> for a,n in zip(name,age):
           print(a,n)
输出:
jack 2001
beginman 2003
sony 2005
pcky 2000
           
all={"jack":2001,"beginman":2003,"sony":2005,"pcky":2000}
for i in all.keys():
    print i,all[i]

输出:
sony 2005
pcky 2000
jack 2001
beginman 2003
           

最显而易见的是:第一种简洁、灵活、而且能顺序输入。

zip()函数

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

s=[2,1]
>>> type(sorted(s))
<type 'list'>
>>> type(zip(s))
<type 'list'>
>>> type(reversed(s))
<type 'listreverseiterator'>
>>> type(enumerate(s))
<type 'enumerate'>
           

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

我们help(zip)看看:

>>> help(zip)
Help on class zip in module builtins:

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |
 |  Methods defined here:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  __next__(self, /)
 |      Implement next(self).
 |
 |  __reduce__(...)
 |      Return state information for pickling.
           

不懂的一定多help

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

>>> z1=[1,2,3]
>>> z2=[4,5,6]
>>> result=zip(z1,z2)
>>> result
[(1, 4), (2, 5), (3, 6)]
>>> z3=[4,5,6,7]
>>> result=zip(z1,z3)
>>> result
[(1, 4), (2, 5), (3, 6)]
>>> 
           

zip()配合*号操作符,可以将已经zip过的列表对象解压

>>> zip(*result)
[(1, 2, 3), (4, 5, 6)]
           

只有一个list的情况:

x = [1, 2, 3]
x = zip(x)
print (x)

运行的结果是:
[(1,), (2,), (3,)]
           

特别注意:在文件读写中也可以运用zip函数

f = open('/home/xbwang/Desktop/id_title','r')
f1 = open('/home/xbwang/Desktop/res','r')
f2 = open('/home/xbwang/Desktop/pos','r')
f3 = open('/home/xbwang/Desktop/cut_pos1','a')
for line,line1,line2 in zip(f,f1,f2):
    line = line[:-1]
    line1 = line1[:-1]
    f3.write(line+'     '+line1+'     '+line2)