码迷,mamicode.com
首页 > 编程语言 > 详细

python3版本中的zip函数

时间:2017-12-15 22:40:34      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:tab   pytho   tle   word   ant   pac   app   orm   stream   

例如,有两个列表:

1
2
>>>a = [1,2,3]
>>>b = [4,5,6]

使用zip()函数来可以把列表合并,并创建一个元组对的列表。

1
2
>>>zip(a,b)
[(1, 4), (2, 5), (3, 6)]<br><br><span style="color: #ff0000;"><strong>#注意在Python3.4版本中,显示<br></strong></span>

>>> zip(a,b)
<zip object at 0x01FB2E90>

如果要显示出结果,必须用list函数

1
在python 3.0zip()是可迭代对象,使用时必须将其包含在一个list中,方便一次性显示出所有结果
1
2
list(zip(a,b))
[(1, 4), (2, 5), (3, 6)]

zip()参数可以接受任何类型的序列,同时也可以有两个以上的参数;当传入参数的长度不同时,zip能自动以最短序列长度为准进行截取,获得元组。

1
2
3
4
5
6
7
8
9
>>> l1,l2,l3 = (1,2,3),(4,5,6),(7,8,9)
>>> list(zip(l1,l2,l3))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
 
 
>>> str1 = ‘abc‘
>>> str2 = ‘def123‘
>>> zip(str1,str2)
[(‘a‘, ‘d‘), (‘b‘, ‘e‘), (‘c‘, ‘f‘)]

搭配for循环,支持并行迭代操作方法

zip()方法用在for循环中,就会支持并行迭代:

1
2
3
4
5
6
7
8
9
l1 = [2,3,4]
l2 = [4,5,6]
 
for (x,y) in zip(l1,l2):
    (print x,y,‘--‘,x*y)
 
2 4 -- 8
3 5 -- 15
4 6 -- 24

python3版本中的zip函数

标签:tab   pytho   tle   word   ant   pac   app   orm   stream   

原文地址:http://www.cnblogs.com/hdk1993/p/8045003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!