内置函数zip()

zip有拉链的意思,zip函数像拉链一样将0个或多个可迭代对象按相同位置组合成一个zip对象,该zip对象的每个元素是由每个可迭代对象的相同位置的元素组成的元祖。

如果zip中有多个序列,而各序列的长度不同,那么返回的对象的长度以最短为准,超出的部分不返回。

如果zip中只有一个序列,则返回对象的每个元祖中只有一个元素。如果zip没有给参数,那么返回一个空对象。

用法:

zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. 
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9,10]

>>> zip(a,b)
<zip object at 0x00000000027D2FC8>
>>> z=zip(a,b)
>>> print(z)
<zip object at 0x00000000027D6088>

>>> for i in z:
...     print(i)
... 
(1, 4)
(2, 5)
(3, 6)
>>> x=zip(a)
>>> for i in x:
...     print(i)
... 
(1,)
(2,)
(3,)
>>> y=zip(a,b,c)
>>> for i in y:
...     print(i)
... 
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)

另外zip函数可以使用星号解开zip对象,即unzip。

zip() in conjunction with the * operator can be used to unzip a list.
>>> m=zip(*zip(a,b,c))
>>> for i in m:
...     print(i)
... 
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)

参考:https://docs.python.org/3/library/functions.html#zip

转载于:https://www.cnblogs.com/keithtt/p/7639167.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值