Skip to main content
 首页 » 编程设计

python之如果我有多个最小数字并且想要两个索引,如何在 python 中找到数组中最小数字的索引

2025年05月04日13myhome

我有一个数组,我想在其中找到最小元素的索引。我尝试了以下方法:

distance = [2,3,2,5,4,7,6] 
 
a = distance.index(min(distance)) 

这将返回 0,这是第一个最小距离的索引。但是,我想找到所有这样的实例,0 和 2。我如何在 Python 中执行此操作?

请您参考如下方法:

使用 np.where 获取匹配给定值的所有索引:

import numpy as np 
 
distance = np.array([2,3,2,5,4,7,6]) 
 
np.where(distance == np.min(distance))[0] 
 
Out[1]: array([0, 2]) 

随着数组大小的增长,Numpy 优于其他方法:

TimeIt 对比测试结果,改编自Yannic Hamann's下面的代码

                     Length of Array x 7 
Method               1       10      20      50     100    1000 
Sorted Enumerate     2.47  16.291  33.643                       
List Comprehension  1.058   4.745   8.843  24.792               
Numpy               5.212   5.562   5.931    6.22  6.441  6.055 
Defaultdict         2.376   9.061  16.116  39.299