python如何获得list或numpy数组中最大元素对应的索引
作者:海晨威 时间:2021-02-10 11:30:12
获得list中最大元素的索引
aa = [1,2,3,4,5]
aa.index(max(aa))
相应的最小值使用
aa = [1,2,3,4,5]
aa.index(min(aa))
获得numpy数组中最大元素的索引
1.可以使用numpy的函数,argmax获得最大元素的索引,相应的获得最小值的话需要使用argmin。
aa = [1,2,3,4,5]
arr_aa = np.array(aa)
maxindex = np.argmax(arr_aa )
1.也可以将numpy转为list,然后使用list或者最大值索引的方法获得最大值。
aa = numpy.array([1,2,3,4,5])
先把aa转换为List,再求索引:
bb = aa.tolist()
bb.index(max(bb))
1.python 比较灵活,所以还可以有其他的方法,如使用where函数。
首先我们可以得到array在全局和每行每列的最大值(最小值同理)
>>> a = np.arange(9).reshape((3,3))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> print(np.max(a)) #全局最大
8
>>> print(np.max(a,axis=0)) #每列最大
[6 7 8]
>>> print(np.max(a,axis=1)) #每行最大
[2 5 8]
然后用where得到最大值的索引,返回值中,前面的array对应行数,后者对应列数
>>> print(np.where(a==np.max(a)))
(array([2], dtype=int64), array([2], dtype=int64)) #表示最大值在第二行第二列
>>> print(np.where(a==np.max(a,axis=0)))
(array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64)) # 表示最大值分别在第二行第零列,第二行第一列,第二行第二列
如果array中有相同的最大值,where会将其位置全部给出
>>> a[1,0]=8
>>> a
array([[0, 1, 2],
[8, 4, 5],
[6, 7, 8]])
>>> print(np.where(a==np.max(a)))
(array([1, 2], dtype=int64), array([0, 2], dtype=int64))
参考文章
1.python 寻找list中最大元素对应的索引
2.python中找出numpy array数组的最值及其索引
来源:https://blog.csdn.net/songyunli1111/article/details/79322103
标签:python,list,numpy,最大元素,索引
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP date函数参数详解
2023-11-23 06:41:40
Python中BeautifuSoup库的用法使用详解
2023-11-19 04:52:48
Check In和Check Out的多人协作管理
2007-02-03 11:39:00
asp关键词屏蔽过滤函数代码
2010-05-04 16:32:00
将tensorflow模型打包成PB文件及PB文件读取方式
2022-07-02 22:47:33
使用pandas对矢量化数据进行替换处理的方法
2022-03-26 06:53:04
Python sklearn CountVectorizer使用详解
2023-06-20 08:19:05
![](https://img.aspxhome.com/file/2023/4/76024_0s.png)
Script块放在另一个Script 块内方法
2009-02-04 15:43:00
解析SQL Server数据体系和应用程序逻辑
2009-01-23 13:58:00
python使用ctypes库调用DLL动态链接库
2023-12-08 14:14:05
![](https://img.aspxhome.com/file/2023/7/95677_0s.png)
何时将数据装载到Application 或 Session 对象中去?
2009-12-03 20:17:00
Pytorch to(device)用法
2022-05-04 22:57:19
python实现聚类算法原理
2022-07-23 23:42:33
![](https://img.aspxhome.com/file/2023/8/80628_0s.gif)
详解Python遍历字典的键和值
2021-07-19 23:02:14
![](https://img.aspxhome.com/file/2023/6/71996_0s.png)
Array.prototype.slice
2010-05-07 12:43:00
Python3 用什么IDE开发工具比较好
2022-10-03 13:43:07
![](https://img.aspxhome.com/file/2023/8/81588_0s.jpg)
Python2.7 实现引入自己写的类方法
2022-02-25 00:07:44
python中pytest收集用例规则与运行指定用例详解
2021-12-01 14:23:21
使用Python完成15位18位身份证的互转功能
2021-11-30 03:04:30
![](https://img.aspxhome.com/file/2023/0/95260_0s.jpg)
Python利用多线程枚举实现获取wifi信息
2021-12-05 03:58:12