python中二维阵列的变换实例
作者:shichen2014 时间:2021-06-28 07:54:06
本文实例讲述了python中二维阵列的变换方法。分享给大家供大家参考。具体方法如下:
先看如下代码:
arr = [ [1, 2, 3], [4, 5, 6], [7, 8,9], [10, 11, 12]]
print map(list, zip(*arr))
print '_-------------------------------------------------'
print [[r[col] for r in arr] for col in range(len(arr[0]))]
运行结果如下:
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
_-------------------------------------------------
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
这里解释一下:
1. 第一种方法:map(list, zip(*arr))
zip([iterable, ...])
This function returns a list of tuples, where the i-th tuple contains thei-th element from each of the argument sequences or iterables.
zip()
这个函数返回一个元组的列表,其中的第i个元组包含从参数传进来的队列的每一个参数的元素的的第I个元素
再举个例子说明一下吧:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
实际上zip(*arr)返回的就是[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)],只不过它的每个元素是元组
map(func, list):
对list中的每个元素调用func方法,返回列表
参数*arr 是python用于传递任意基于位置的参数的语法
2. 第二种方法: [[r[col] for r in arr] for col in range(len(arr[0]))]
内层推导改变的是(从行中)选出的元素, 外层推导则影响了选择子(即列)
希望本文所述对大家的Python程序设计有所帮助。
标签:python
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
自然语言处理之文本热词提取(含有《源码》和《数据》)
2021-11-26 11:14:58
人工智能学习Pytorch教程Tensor基本操作示例详解
2021-06-14 17:39:22
![](https://img.aspxhome.com/file/2023/6/117936_0s.png)
asp如何创建一个Exchange用户?
2009-11-14 20:52:00
sql如何在线创建新表?
2010-06-22 21:21:00
pandas进行时间数据的转换和计算时间差并提取年月日
2021-03-14 02:22:22
![](https://img.aspxhome.com/file/2023/7/109477_0s.png)
JavaScript中的this/call/apply/bind的使用及区别
2023-09-15 06:23:19
Python3.5 Pandas模块之Series用法实例分析
2022-07-23 16:19:09
![](https://img.aspxhome.com/file/2023/1/76181_0s.png)
浅谈JavaScript的自动垃圾收集机制
2023-08-13 15:18:57
python实现神经网络感知器算法
2021-03-06 11:23:39
![](https://img.aspxhome.com/file/2023/9/91979_0s.png)
bpython 功能强大的Python shell
2022-05-08 22:12:06
![](https://img.aspxhome.com/file/2023/9/100909_0s.png)
W3C优质网页小贴士(四)
2008-04-17 13:34:00
Python supervisor强大的进程管理工具的使用
2021-04-15 09:11:58
![](https://img.aspxhome.com/file/2023/0/75150_0s.png)
Pycharm中配置远程Docker运行环境的教程图解
2022-08-06 09:39:19
![](https://img.aspxhome.com/file/2023/8/97278_0s.png)
Python线性网络实现分类糖尿病病例
2022-03-13 11:23:25
![](https://img.aspxhome.com/file/2023/9/70179_0s.png)
Python图像处理之图像的灰度线性变换
2021-12-16 22:30:58
![](https://img.aspxhome.com/file/2023/7/65977_0s.png)
如何将一个CSV格式的文件分割成两个CSV文件
2022-02-17 01:24:29
asp如何实现歌曲在线点播?
2010-05-19 21:32:00
Python中re.findall()用法详解
2023-08-09 23:46:14
![](https://img.aspxhome.com/file/2023/1/61191_0s.png)
python 第三方库的安装及pip的使用详解
2023-12-27 07:06:53
![](https://img.aspxhome.com/file/2023/9/65019_0s.png)
Pandas查询数据df.query的使用
2021-06-09 03:48:47