下面是python3的解释:
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.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
举例说明:
l1 = [1,2,3,4,5]
l2 = [11,22,33,44,55]
l3 = zip(l1,l2)
print(l3)
for i in l3:
print(i)
结果如下:
<zip object at 0x7fb1d1676a48>
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)
python2和python3的区别在于,python2是直接返回一个新列表,列表的元素是元组,形如:
[(1, 11), (2, 22), (3, 33), (4, 44), (5, 55)]
python3则是返回一个生成器。
练习
现有两个列表:
l1 = [12, 34, 55, 4, 3, 56, 7, 3, 2]
l2 = [21, 43, 22, 7, 34, 3, 23, 2, 8]
将两个列表按下标一一对应,求较大值,返回一个新的列表。
结合列表生成式和zip函数,可以很方便求出结果:
l3 = [x if x > y else y for x, y in zip(l1, l2)]
print(l3)
结果如下:
[21, 43, 55, 7, 34, 56, 23, 3, 8]