Python 的zip函数
来源:互联网 发布:mc喊麦软件 编辑:程序博客网 时间:2024/05/16 10:55
zip是Python 的内置函数,简言之,实现矩阵的转置。
比如,给出4x2矩阵
1 52 63 74 8
通过zip函数,可以得到它的2x4转置矩阵
1 2 3 45 6 7 8
具体做法是:把前面的4x2矩阵表示为两个向量的列表,向量可以用列表(list)或者元组(tuple)表示,但是zip返回的一定是tuple表示的向量:
>>> x = (1, 2, 3, 4)>>> y = (5, 6, 7, 8)>>> zip(x,y)[(1, 5), (2, 6), (3, 7), (4, 8)] #得到2x4转置矩阵>>> z = (9, 10, 11, 12) >>> zip(x,y,z) #再加一列[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] #得到3x4转置矩阵
可以看出zip的参数是多个向量,zip函数定义为:
def zip(seq1, seq2, *more_seqs):
返回多个向量组成的列表(list of tuple)
[tuple1, tuple2,...]
如果要把得到的转置矩阵再次转置,只要把向量的列表用号解开传给zip就可以了,因为用号解开后,仍然是zip需要的多个向量:
>>> T = zip(x,y,z)>>> T[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] #转置后的矩阵>>> zip(*T) #用*号解开传给zip[(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)] #得到再次转置的矩阵
zip函数的一个用处,是将key和value两个list构造成dict函数所需的(key, value)对,以生成一个字典。就像把拉链两边拉起来成为一个完整的拉链一样。
>>> name = ['Alice', 'Ben', 'Celia', 'Dave']>>> age = [12, 13, 14, 15]>>> keypair = zip(name, age)>>> keypair[('Alice', 12), ('Ben', 13), ('Celia', 14), ('Dave', 15)]>>> dict(keypair){'Dave': 15, 'Ben': 13, 'Alice': 12, 'Celia': 14}
原文链接:http://www.lfhacks.com/tech/python-zip
0 0
- Python的zip函数
- Python的zip函数
- Python的zip函数
- Python的zip函数
- Python的zip函数
- python的zip函数
- Python的zip函数
- Python的zip函数
- Python的zip函数
- Python 的zip函数
- Python的zip函数
- python 的 zip 函数
- python的zip函数
- Python的zip函数
- Python的zip函数
- Python的zip函数
- Python的zip函数
- python的zip函数
- distribute mysql
- serialVersionUID的作用
- 日报
- 在Matlab中读取、写入二进制数据文件
- 建站
- Python 的zip函数
- 原理图,PCB设计软件
- iOS--MultipeerConnectivity蓝牙通讯
- 在DOS窗口下不能正常使用net命令
- hadoop家族介绍
- Bitmap算法
- shell 获得本机IP和free端口
- Web安全之权限攻击
- 192.168.148.215\sql2000连不上