python zip用法
2015-10-07 14:56
369 查看
zip()配合*号操作符,可以将已经zip过的列表对象解压
z1=[1,2,3]
z2=[4,5,6]
result = zip(z1,z2)
result
Out[9]: [(1, 4), (2, 5), (3, 6)]
zip(*result)
Out[10]: [(1, 2, 3), (4, 5, 6)]
z1=[1,2,3]
z2=[4,5,6]
result = zip(z1,z2)
result
Out[9]: [(1, 4), (2, 5), (3, 6)]
zip(*result)
Out[10]: [(1, 2, 3), (4, 5, 6)]
* 二维矩阵变换(矩阵的行列互换) 比如我们有一个由列表描述的二维矩阵 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]] zip函数接受任意多个序列作为参数,将所有序列按相同的索引组合成一个元素是各个序列合并成的tuple的新序列,新的序列的长度以参数中最短的序列为准。另外(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple。 ①tuple的新序列 >>>>x=[1,2,3],y=['a','b','c'] >>>zip(x,y) [(1,'a'),(2,'b'),(3,'c')] ②新的序列的长度以参数中最短的序列为准. >>>>x=[1,2],y=['a','b','c'] >>>zip(x,y) [(1,'a'),(2,'b')] ③(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple。 >>>>x=[1,2,3],y=['a','b','c'] >>>>zip(*zip(x,y)) [(1,2,3),('a','b','c')]
相关文章推荐
- 【Python】Learn Python the hard way, ex14 argv参数传值
- 使用 Python 进行线程编程
- python模糊查询
- Python标准库的学习准备
- Python标准库——走马观花
- <PY>感知机
- python设计模式1:创建型模式
- 6.Python补充_Python之道
- 5.Python补充_字符串格式化 (%操作符)
- 4.Python补充_Python简史
- windows下使用cx_freeze将Python程序打包成exe可执行文件
- Python 全局变量的使用
- 【Python】Learn Python the hard way, ex13 传递参数
- Python 3.0 和 2.X的简单区别
- Python的ipython的安装
- 【Python】Learn Python the hard way, ex12 raw_input 提示别人
- python 如何找到某一目录下的文件类型(三种方法)
- 【Python】Learn Python the hard way, ex11 raw_input
- 【Python】Learn Python the hard way, ex10 转义字符
- 【Python】Learn Python the hard way, ex9 换行符,打印多行字符