【Python】zip 函数

Backto Python Index

zip 函数是Python里面具有代表性、超好用的 built-in 函数之一。其作用就是,给定任意多个 sequence,把相同下标的元素组合成tuple,再返回。简化了一大票操作。

对于Python2 中的 zip 返回的是一个 tuple 的 list。

Help on built-in function zip in module __builtin__:

zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.
None

---

x = [1, 2, 3]
y = ['a', 'b', 'c', 'd']
xy = zip(x, y)
print xy

#结果是:
[(1, 'a'), (2, 'b'), (3, 'c')]

到了 Python3 中,就随着大趋势,变成了返回 zip class 对象了。


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.


L1 = [1,2,3,4,5] 
L2 = ['A','B','C','D','E'] 
print(zip(L1,L2))
=> <zip object at 0x000000000260ED08>
print(list(zip(L1,L2))) 
=> [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]

Ref

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值