python中的zip函数使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Martin201609/article/details/53283449

1.函数的介绍
python zip函数使用
zip函数的用法: 接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。
接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。

>>> 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.

返回值: a list of tuples
处理方式: 当多个列表的不同长度时候,取最少的一个列表长度作为基准,进行处理

2. 功能演示
2.1 示例一

lista = ['a','b','c']
listb = [1,2,3]
listc = zip(lista,listb)
print listc
#输出:
[('a', 1), ('b', 2), ('c', 3)]
将列表对应的元素,合成tuple,并存放成list返回

2.2 示例二
当两个list大小不一样时

lista = ['a','b','c']
listb = [1,2,3,4]
listc = zip(lista,listb)
print listc
listd = zip(listb,lista)
print listd
#输出:
[('a', 1), ('b', 2), ('c', 3)]
[(1, 'a'), (2, 'b'), (3, 'c')]

当list大小不一致,则截取共同的进行合并

2.3 示例三

lista = ['a','b','c']
listb = [1,2,3,]
listc = ['x','y','z']
d = zip(lista,listb,listc)
print d
#输出
[('a', 1, 'x'), ('b', 2, 'y'), ('c', 3, 'z')]

2.4 网上看到更深层次的引用
引用网址:
http://www.cnblogs.com/BeginMan/archive/2013/03/14/2959447.html

* 二维矩阵变换(矩阵的行列互换)
比如我们有一个由列表描述的二维矩阵
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
通过python列表推导的方法,我们也能轻易完成这个任务
print [ [row[col] for row in a] for col in range(len(a[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
另外一种让人困惑的方法就是利用zip函数:
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> map(list,zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

猜你喜欢

转载自blog.csdn.net/Martin201609/article/details/53283449