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 opencv图片编码为h264文件的实例

python部分 #!/usr/bin/env Python # coding=utf-8 from ctypes import * from PyQt5.QtCore impo...

python计算阶乘和的方法(1!+2!+3!+...+n!)

方法一:使用while循环来计算 n = int(input()) jie = 1 sum = 0 i = 1 while n >= i: jie = jie * i...

Python自动化测试工具Splinter简介和使用实例

Splinter 快速介绍官方网站:http://splinter.cobrateam.info/官方介绍:Splinter is an open source tool for tes...

基于Python解密仿射密码

基于Python解密仿射密码

新学期有一门密码学课,课上老师布置了一道密码学题,题目如下: 解密由仿射密码加密的密文“DBUHU SPANO SMPUS STMIU SBAKN OSMPU SS” 想解密这个密文,首...

Python采用raw_input读取输入值的方法

本文较为详细的介绍了python中raw_input的用法,使用raw_input 能够很方便的丛控制台读入数据。具体用法示例如下: 1.输入字符串 #13222319810101*...