zip函数介绍
zip( *iterables )
返回一个迭代器,聚合来自每个可迭代对象的元素。
返回元组的迭代器,其中第i个元组包含来自每个参数序列或可迭代对象的第i个元素。当最短的输入迭代用完时,迭代器停止。使用单个可迭代参数,它返回一个 1 元组的迭代器。没有参数,它返回一个空的迭代器。
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
<zip object at 0x000001EAEAB6D300>
>>> type(zipped)
<class 'zip'>
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x1, y1, z1 = zip(x, y)
>>> x1
(1, 4)
>>> y1
(2, 5)
>>> z1
(3, 6)
zip()与*操作符结合可用于解压缩列表
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(*zipped))
[(1, 2, 3), (4, 5, 6)]
list算术减操作(zip的常见应用)
对于两个list相对应元素的算术操作,例如两个list相减,因为两个list无法直接做算术减操作的。
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a - b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
因此需要利用map函数与zip函数,然后对两个list的相对应元素相减:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> res = map(lambda x: x[0] - x[1], zip(a, b))
>>> res
<map object at 0x000001EAEAB7B820>
>>> list(res)
[-3, -3, -3]