以前使用zip
,只用过最简单的,合并两个列表,没有仔细深究过,后来在实验楼 做实验的时候,遇到了这样的一行代码:
[list(row) for row in zip(*field)]
有点蒙了, 就查了查了,这俩博客的介绍挺仔细的
Python零碎知识(2):强大的zip ,
Python的zip函数
记录一下吧
zip()的基本使用方法
首先看help(zip)
:
Help on built-in function zip in module __builtin__: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.None
大意就是:
定义:zip([seql, …])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。
通俗点就是把几个列表(0或者1或者多个)的对应位置的元素组成新的tuple
, 这些新的tuple
构成一个list
.
直接用几个例子来说明:
示例
x = [1, 2, 3]y = [4, 5, 6]z = [7, 8, 9]xyz = zip(x, y, z)print xyz'''结果是:'''[(1, 4, 7), (2, 5, 8), (3, 6, 9)]x = zip()print x[]x = [1, 2, 3]y = ['a', 'b', 'c', 'd']xy = zip(x, y)print xy[(1, 'a'), (2, 'b'), (3, 'c')]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
常用的方法
x = [[1,2,3], [4,5,6], [7,8,9]]y = zip(*x)print y[(1, 4, 7), (2, 5, 8), (3, 6, 9)]map(list, y) x = [1, 2, 3]y = [4, 5, 6]z = [7, 8, 9]xyz = zip(x, y, z)res = zip(*xyz)print res[(1, 2, 3), (4, 5, 6), (7, 8, 9)]''''''x = ['a', 'b', 'c']y = ['x', 'y', 'z']z = zip(x, y)d = dict(z)print d{'a': 'x', 'c': 'z', 'b': 'y'}''''''a = [1, 2, 3, 4, 5, 6]b = zip(*([iter(a)] * 2))print b[(1, 2), (3, 4), (5, 6)]
http://blog.csdn.net/shomy_liu/article/details/46968651