python zip函数_Python的zip()函数用法

Python内置一个zip函数,这里不是压缩的意思,而是将数据组合在一起,zip起来,zip本身就还有拉链的意思哦。那么,zip这个函数,组合什么呢?将多个序列组合成一个复合序列。

看下面示例代码:

>>>

>>> listA = [1,2,3]

>>> listB = [4,5,6]

>>> listA

[1, 2, 3]

>>> listB

[4, 5, 6]

>>> zip(listA,listB)

>>> list(zip(listA,listB))

[(1, 4), (2, 5), (3, 6)]

>>>

>>> listB.append(7)

>>> listB

[4, 5, 6, 7]

>>> list(zip(listA,listB))

[(1, 4), (2, 5), (3, 6)]

>>>

>>> list(zip(listA))

[(1,), (2,), (3,)]

>>>

>>> list(zip('abcd','12345'))

[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]

>>>

>>> tuple(zip('abcd','12345'))

(('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'))

>>>

>>>

官方对zip函数的解释:

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.

超过两个iterable的参数也是可以的:

>>>

>>> k = zip([1,2,3],[4,5,6],[7,8,9])

>>> k

>>> list(k)

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

>>>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值