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

yipeiwu_com7年前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调用c++返回带成员指针的类指针实例

这个是OK的: class Rtmp_tool { public: int m_width; AVCodecContext * c; }; 指针的用法如下: Rtm...

Python使用正则表达式分割字符串的实现方法

如下: re.split(pattern, string, [maxsplit], [flags]) pattern:表示模式字符串,由要匹配的正则表达式转换而来。 string...

python 中字典嵌套列表的方法

如下所示: >>> dict={} >>> dict['list']=[] >>> dict['list'].append([1...

wxpython绘制圆角窗体

本文实例为大家分享了wxpython绘制圆角窗体的具体代码,供大家参考,具体内容如下 # -*- coding:gbk -*- import wx class RCDialo...

python url 参数修改方法

基于python 3.5,python 2.7 与python3.4 的urllib不同,是urlparse >>> from urllib import pars...