首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python zip()方法

python zip()方法

作者头像
周小董
发布2019-03-25 11:21:57
7470
发布2019-03-25 11:21:57
举报
>>> 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)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年08月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • zip()函数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档