- zip是什么?
zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
a = [1,2,3,4]
b = [4,5,6]
print zip(a,b)
返回:[(1, 4), (2, 5), (3, 6)]
a = [1,2,3,4]
b = [4,5,6,10]
c= [7,8,9]
print zip(a,b,c)
返回: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Note:zip它的参数必须是一个序列类型的,如果是字典,那么键值就是序列:
e.g
aDic = {'a':'Hello', 'b':'Python'}
bDic = {'c':'I','d':'Like'}
print zip(aDic,bDic)
返回: [('a', 'c'), ('b', 'd')]
zip 可以转换为Dictionary哦:
例如相将
aDic = {'a':'Hello', 'b':'Python'}
转换为:
aDic = {'Hello':'a', 'Python':'b'}
怎么转?
用zip:
print dict(zip(aDic.values(),aDic.keys()))
返回:{'Python': 'b', 'Hello': 'a'}, 是不是超级简洁?