Python中如何获得数组或者列表按大小排序的索引

您所在的位置:网站首页 python输出数组的索引号 Python中如何获得数组或者列表按大小排序的索引

Python中如何获得数组或者列表按大小排序的索引

2024-07-16 06:49| 来源: 网络整理| 查看: 265

(1)自定义方法

myList = [1, 2, 3, 100, 5] index_list=[i[0] for i in sorted(enumerate(myList), key=lambda x:x[1])]

enumerate(myList)返回一个包含(index,value)元组的列表

[(0, 1), (1, 2), (2, 3), (3, 100), (4, 5)]

通过将列表传递给排序并指定一个函数来抽取排序键(每个元组的第二个元素;这是lambda的用途),最后,每个排序的元素的原始索引使用[i [0 ] for i in …]列表解析。 

来自:https://codeday.me/bug/20170625/33969.html 

(2)np.argsort函数

import numpy as np a = np.array([1,4,3,5,2]) b = np.argsort(a) print(b)

print结果为[0 4 2 1 3] ,即为从小到大排序的索引

来自:https://blog.csdn.net/guotong1988/article/details/78790210

(3) 利用heapq模块

# -*- 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/ns2250225/article/details/80118621

这里利用了数组自身属性 index,

list.index(target), 其中list是目标list,target是需要的下标对应的值,返回对应的索引值

map函数的返回值是一个 iterators,所以打印这里加一个list强制输出所有

推荐前两种方法, 第三种不推荐,第三种遇到相同大小的时候会都返回第一个位置的索引

例如求如下列表中最大的三个数字的索引

# -*- coding: utf-8 -*- __author__ = 'fff_zrx' import heapq import numpy as np test_list= [1,2,3,3,4] index_list=[i[0] for i in sorted(enumerate(test_list), key=lambda x:x[1])] b = np.argsort(np.array(test_list)) max_num_index_list = map(test_list.index, heapq.nlargest(3, test_list)) print("第一种:",index_list[-3:][::-1]) print("第二种:",b[-3:][::-1]) print("第三种:",list(max_num_index_list))

输出为:

第一种: [4, 3, 2] 第二种: [4 3 2] 第三种: [4, 2, 2] 

ps:a[::-1]相当于 a[-1:-len(a)-1:-1],即倒序输出,前两者默认都是从小到大排序的索引,所以需要倒序输出一下

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3