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
- Python: zip()的使用: 总结的很全面
- Python版本3.3有zip这个用法吗? - 张雨萌-酱油哥的回答 - 知乎: Python 2 VS Python 3