zip函数(含代码示例)

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习的贝塔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值