先贴上源码:
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'),(1,2,3,4,5)))
A0 = {{'e': 5, 'd': 4, 'a': 1, 'b': 2, 'c': 3}}
如果是
A0 = list(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A0 = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]