zip函数的用法

下面是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]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值