python 找出list中最大或者最小几个数的索引方法

yipeiwu_com6年前Python基础

如下所示:

nums = [1,8,2,23,7,-4,18,23,24,37,2]
result = map(nums.index, heapq.nlargest(3, nums))
temp=[]
Inf = 0
for i in range(3):
  temp.append(nums.index(max(nums)))
  nums[nums.index(max(nums))]=Inf
result.sort()
temp.sort()
print(result)
print(temp)

如上,有result和temp两种求法,上面代码输出:

[3, 8, 9]
[3, 8, 9]

没问题

但是把nums改一下:

nums = [1,8,2,23,7,-4,18,23,23,37,2]

输出:

[3, 3, 9]
[3, 7, 9]

发现问题了吧,result方法发现相同数字永远会返回第一次出现的索引。

以上这篇python 找出list中最大或者最小几个数的索引方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python matplotlib 在指定的两个点之间连线方法

python matplotlib 在指定的两个点之间连线方法

为了找到matplotlib在两个点之间连线的方法真是费了好大功夫,最后还是决定用简单的 plt.plot 来解决。如果有好多对点,则可以通过循环实现连接,还可以用 plt.arrow...

Python实现曲线拟合操作示例【基于numpy,scipy,matplotlib库】

Python实现曲线拟合操作示例【基于numpy,scipy,matplotlib库】

本文实例讲述了Python实现曲线拟合操作。分享给大家供大家参考,具体如下: 这两天学习了用python来拟合曲线。 一、环境配置 本人比较比较懒,所以下载的全部是exe文件来安装,安装...

python列表每个元素同增同减和列表元素去空格的实例

python列表每个元素同增同减和列表元素去空格的实例

如下所示: import os var = [1, 2, 3] data = [x*2 for x in var] print (data) two = [[i, i**2] f...

Python+selenium 获取一组元素属性值的实例

获取一组href元素属性的值 lst = driver.find_elements_by_class_name("ib-it-text") for lst in lst: lst...

在Python中移动目录结构的方法

来源:http://stackoverflow.com/questions/3806562/ways-to-move-up-and-down-the-dir-structure-in-p...