Python中交换两个元素的实现方法
作者:河流儿 时间:2023-07-29 08:28:15
Python既具有普通程序开发语言的特点,也具有Matlab语言用于数值计算的特点,,当然了数值计算是由其其强大的第三方库numpy实现的,矩阵在python中数据类型是ndarray,python中交换两个数值的代码和交换同一矩阵(ndarray)中不同向量的写法是不一样的。
以下是用Python原生的数据结构list实现的交换
>> a = [1,2,3]
>> b = [4,5,6]
>> a
[1,2,3]
>> b
[4,5,6]
>> a,b = b,a
>> a
[4,5,6]
>> b
>[1,2,3]
以下是numpy中交换矩阵中两列元素的方法
>> import numpy as np
>> a = np.array([[1,2,3],[4,5,6]])
>> a
array([[1, 2, 3],
[4, 5, 6]])
>> a[:,0],a[:,-1] = a[:,-1],a[:,0]
>> a
array([[3, 2, 3],
[6, 5, 6]])
>> a[:,[0, -1]] = a[:,[-1, 0]]
>> a
array([[3, 2, 1],
[6, 5, 4]])
上面代码是将同一矩阵的第一列和最后一列进行了交换,可见,用第一种的写法是错误的,第二种正确。
注意: 交换再同一矩阵中的不同行才要这样写,如果是不同矩阵的话按第一种写法就可以了
来源:https://blog.csdn.net/github_34777264/article/details/78879481
标签:Python,交换,元素
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pycham查看程序执行的时间方法
2022-12-25 20:41:47
MySQL中使用or、in与union all在查询命令下的效率对比
2024-01-16 02:28:45
![](https://img.aspxhome.com/file/2023/3/128373_0s.jpg)
Python基于进程池实现多进程过程解析
2023-05-08 10:52:24
使用pytorch进行张量计算、自动求导和神经网络构建功能
2022-08-18 11:50:48
教你快速了解公共MySQL的数据库服务器层
2008-12-17 17:10:00
详解Python爬虫爬取博客园问题列表所有的问题
2021-02-15 02:01:46
![](https://img.aspxhome.com/file/2023/8/109658_0s.jpg)
python从PDF中提取数据的示例
2021-10-15 21:46:05
![](https://img.aspxhome.com/file/2023/2/99462_0s.png)
python 实现数据库中数据添加、查询与更新的示例代码
2023-10-08 04:09:51
mysql4.1以上版本连接时出现Client does not support authentication protocol问题解决办法
2023-11-18 06:10:15
很快大多数网民将放弃IE浏览器
2009-02-04 16:43:00
![](https://img.aspxhome.com/file/UploadPic/20092/5/browsersfeb09-86s.jpg)
Python读取postgresql数据库详情
2024-01-29 13:01:17
![](https://img.aspxhome.com/file/2023/2/131752_0s.png)
wxPython色环电阻计算器
2023-12-21 20:08:54
JS如何实现在弹出窗口中加载页面
2024-04-29 14:07:53
![](https://img.aspxhome.com/file/2023/7/130867_0s.gif)
记一次pyinstaller打包pygame项目为exe的过程(带图片)
2023-12-29 12:45:19
![](https://img.aspxhome.com/file/2023/7/124127_0s.png)
Python3操作YAML文件格式方法解析
2021-05-22 03:57:10
Python实现带参数的用户验证功能装饰器示例
2023-05-15 01:34:05
解决Python中定时任务线程无法自动退出的问题
2022-09-05 22:52:52
深入Python解释器理解Python中的字节码
2022-04-28 18:29:33
![](https://img.aspxhome.com/file/2023/4/123844_0s.jpg)
Java正则表达式的基本用法和实例大全
2023-04-14 06:17:22
![](https://img.aspxhome.com/file/2023/8/90028_0s.png)
flask应用部署到服务器的方法
2023-11-25 16:59:38
![](https://img.aspxhome.com/file/2023/9/98329_0s.png)