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设计】。

相关文章

解析PyCharm Python运行权限问题

解析PyCharm Python运行权限问题

先通过 which python 获得 python 指令所在路径: $ which python /usr/bin/python 如上得到了其所在路径是 /usr/bin/pyt...

python使用numpy读取、保存txt数据的实例

python使用numpy读取、保存txt数据的实例

1.首先生成array数组 import numpy as np a = np.random.rand(5,5) print(a) 结果: array([[0.17374613...

Ubuntu+python将nii图像保存成png格式

这里介绍一个nii文件保存为png格式的方法。 这篇文章是介绍多个nii文件保存为png格式的方法: /post/165692.htm 系统:Ubuntu 16.04 软件: pytho...

Python 编码Basic Auth使用方法简单实例

本片博文主要介绍在Python3 环境下把用户名密码编码成字符串。 代码如下: import base64 def get_basic_auth_str(username, pass...

使用Python中的线程进行网络编程的入门教程

引言 对于 Python 来说,并不缺少并发选项,其标准库中包括了对线程、进程和异步 I/O 的支持。在许多情况下,通过创建诸如异步、线程和子进程之类的高层模块,Python 简化了各种...