Python zip
zip([iterable, ...])
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。
若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。
利用*号操作符,可以将list unzip(解压)。
>>> x=[1,2,3] >>> y=[4,5,6] >>> z=[7,8,9,10] >>> xy=zip(x,y) >>> xy [(1, 4), (2, 5), (3, 6)] >>> zip(*xy) [(1, 2, 3), (4, 5, 6)] >>> zip(y,z) [(4, 7), (5, 8), (6, 9)] >>> zip(xrange(4),z) [(0, 7), (1, 8), (2, 9), (3, 10)] >>> zip(x) [(1,), (2,), (3,)] >>> zip() [] >>> zip(*[[1,2]]*2) [(1, 1), (2, 2)]
行列变换
m1=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] print [[elment[i] for elment in m1] for i in range(len(m1[0]))] [[1, 4, 7], [2, 5, 8], [3, 6, 9]] zip(*m1) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] map(list,zip(*m1)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]