python中的zip函数

先贴上源码:

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.
   意思:zip里面接收的是可迭代对象,依次取值,返回的是一个元组
使用举例:

一、传入一个可迭代对象(列表为例,也可以传入元组、集合):
如果传入字典,只取键值拼接为元组
a = [1, 2, 3]
b = zip(a)
print(b)--><zip object at 0x7f1122bdb608>
print(list(b))-->[(1,), (2,), (3,)]
print(tuple(b))-->((1,), (2,), (3,))
print(dict(b))-->报错ValueError
如果传入字典
a = {1:2, 3:4}
b = zip(a)
print(tuple(b))-->((1,), (3,))

二、传入两个可迭代对象
a = [1, 2, 3]
b = [8, 9, 0]
c = zip(a, b)
print(tuple(c))-->((1, 8), (2, 9), (3, 0))
传入两个字典
a = {1:2, 3:4}
b = {8:9, 7:0}
c = zip(a, b)
print(tuple(c))-->((1, 8), (3, 7))

面试题分析:
A0 = dict(zip(('a''b''c''d''e')(12345)))
A0 = {{'e': 5, 'd': 4, 'a': 1, 'b': 2, 'c': 3}}
如果是
A0 = list(zip(('a''b''c''d''e')(12345)))
A0 = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值