python topN 取 最大的N个数 或 最小的N个数

news/2024/7/24 3:11:24
import numpy as np 
a = np.array([1,4,3,5,2]) 
b = np.argsort(a) 
print(b)

print结果[0 4 2 1 3] 
说明a[0]最小,a[3]最大

a[0]<a[4]<a[2]<a[1]<a[3]

这里要借助到python的内置模块heapq,其原理是基于堆的,也就是二叉树

import heapq
 
a=[1,2,3,4,5]
re1 = map(a.index, heapq.nlargest(3, a)) #求最大的三个索引    nsmallest与nlargest相反,求最小
re2 = heapq.nlargest(3, a) #求最大的三个元素
print(list(re1)) #因为re1由map()生成的不是list,直接print不出来,添加list()就行了
print(re2) 

输出结果为

[4, 3, 2]
[5, 4, 3]

 

# -*- coding: utf-8 -*-
import heapq

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

# 最大的3个数的索引
max_num_index_list = map(nums.index, heapq.nlargest(3, nums))

# 最小的3个数的索引
min_num_index_list = map(nums.index, heapq.nsmallest(3, nums))

print(list(max_num_index_list))
print(list(min_num_index_list))

参考:

https://blog.csdn.net/qq_41973536/article/details/84865595

https://blog.csdn.net/ns2250225/article/details/80118621


http://www.niftyadmin.cn/n/957725.html

相关文章

这样写之出来一个0,没有出来bar

<template><title>陈尼克</title><div id"app">{{ count }} {{ object.foo }}</div> </template><script> //import { defineProps, reactive } from vueimport { createApp, ref, reactive } from vue; //const { create…

【SpringBoot实战】分布式定时任务锁Shedlock

在我们业务开发过程中&#xff0c;经常会有需求做一些定时任务&#xff0c;但是由于定时任务的特殊性&#xff0c;以及一些方法的幂等性要求&#xff0c;在分布式多节点部署的情况下&#xff0c;某个定时任务只需要执行一次。 1. 背景介绍 ShedLock(https://github.com/lukas…

怎么改成1 foo呢?

改得不对 <template><title>陈尼克</title><div id"app">{{ count }} {{ object.foo }}</div> </template><script> //import { defineProps, reactive } from vueimport { createApp, ref, reactive } from vue; //cons…

keras 预测采坑

训练数据集如果经过了 # x_test x_test.astype(float32) # x_test / 255 处理&#xff0c; 预测用数据也要经过同样的处理....

计时器setTimeout()方法的用法,怎样改变成1 foo

<template><title>陈尼克</title><div>{{ count }} {{ object.foo }}</div> </template><script> //import { defineProps, reactive } from vue//import { createApp, ref, reactive } from vue; import { ref, reactive } from vu…

keras预测函数采坑实录

使用两种方法构建模型&#xff0c;一种是如下所示方法&#xff0c;构建一个VGG16网络&#xff1a; model Sequential()model.add(Conv2D(32, (3, 3), strides(1, 1), input_shape(299, 299, 3), paddingsame, activationrelu,kernel_initializeruniform))model.add(Conv2D(32,…

如何获取用户的微信openid

如何获取用户的微信openid 如何获取用户的微信openid &#xff08;1&#xff09;首先登陆微信公众号后台&#xff08;确保你有登陆微信后台的权限才可以哦&#xff09;&#xff08;2&#xff09;登陆后点击左侧“用户管理”&#xff0c;然后找到你要查的用户&#xff0c;右击头…

keras yolov3 Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED

训练、测试Tensorflow、Keras代码时&#xff0c;出现could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED、error retrieving driver version: Unimplemented: kernel reported driver version not implemented on Windows、could not destroy cudnn handle: CUDNN_S…