Python——list返回最大的K个元素的索引

自定义的一个有用的Python方法


返回最大的K个值的索引

引用自Stack Overflow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def get_top_k_indexes_of_list(target_list, k, is_max=True, min_value=None):
"""
get the top k indexes of elements in list
Example:
Problem: I have a list say a = [5,3,1,4,10],
and I need to get a index of top two values of the list viz 5 and 10.
Is there a one-liner that python offers for such a case?
Usage: get_top_k_indexes_of_list(target_list=a, k=2, is_max=True)
link: https://stackoverflow.com/questions/13070461/get-index-of-the-top-n-values-of-a-list-in-python
:param target_list: target list
:param k: the number of indexes
:param is_max: True means max else False means min
:param min_value: if min_value is not None
filter the indexes whose value less than or equals to min_value
:return: a list of indexes
"""
indexes = sorted(range(len(target_list)), key=lambda i: target_list[i], reverse=is_max)[:k]
result = list()
if min_value is not None:
for index in indexes:
if target_list[index] <= min_value:
break
result.append(index)
else:
result = indexes
return result

一次性索引出多个元素

1
2
3
4
5
6
7
8
9
def get_elements_from_list(target_list, indexes):
"""
get elements from target_list by indexes
:param target_list: target list
:param indexes: a list of indexes
:return: a list of elements
"""
elements = [target_list[i] for i in indexes]
return elements