标签:
zip: 接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后再返回这些元组组成的list。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同
>>> a = [1,2,3]
>>> b = [‘a‘,‘b‘,‘c‘]
>>> z = zip(a,b)
>>> z
[(1, ‘a‘), (2, ‘b‘), (3, ‘c‘)]
>>> zip(*z)
[(1, 2, 3), (‘a‘, ‘b‘, ‘c‘)]
合并相邻的列表项:
>>> a = [1,2,3,4,5,6]
>>> zip(*([iter(a)]*2))
[(1, 2), (3, 4), (5, 6)]
>>> zip(*([iter(a)]*3))
[(1, 2, 3), (4, 5, 6)]
反转字典:
>>> m = dict(a=1,b=2,c=3,d=4)
>>> m
{‘a‘: 1, ‘c‘: 3, ‘b‘: 2, ‘d‘: 4}
>>> zip(m.values(),m.keys())
[(1, ‘a‘), (3, ‘c‘), (2, ‘b‘), (4, ‘d‘)]
标签:
原文地址:http://www.cnblogs.com/zxahu/p/4757900.html