[英]find top k largest item of a list in original order in python
say I have the following list:说我有以下列表:
my_list = [3.5, 1.6, 2.4, 8.9, 5.6]
I want to find the top 3 largest number in its original place, so the result should be:我想在原来的地方找到前3个最大的数,所以结果应该是:
[3.5, 8.9, 5.6]
How could I do that?我怎么能那样做? I think I can find the 3 largest number and use a filter, but I think it may not be a good idea to compare floats.我想我可以找到最大的 3 个数字并使用过滤器,但我认为比较浮点数可能不是一个好主意。 Any suggestions?有什么建议么?
>>> import heapq
>>> heapq.nlargest(3, my_list)
[8.9, 5.6, 3.5]
Add a little polish to the same idea, to keep them in original order:为相同的想法添加一点润色,以保持它们的原始顺序:
>>> from operator import itemgetter
>>> i_val = heapq.nlargest(3, enumerate(my_list), key=itemgetter(1))
>>> [val for (i, val) in sorted(i_val)]
[3.5, 8.9, 5.6]
You can sort the index-value pairs (generated by enumerate
) by the value, get the last three pairs, and then sort those by the index (and then get just the values from the index-value pairs, all this in a one-liner list comprehension):您可以按值对索引值对(由enumerate
生成)进行排序,获取最后三对,然后按索引对它们进行排序(然后仅从索引值对中获取值,所有这些都在一个-班轮列表理解):
from operator import itemgetter
my_list = [3.5, 1.6, 2.4, 5.6, 8.9]
result = [p[1] for p in sorted(sorted(enumerate(my_list), key = itemgetter(1))[-3:], key = itemgetter(0))]
print(result)
Output: Output:
[3.5, 5.6, 8.9]
Here you go, you can try with this function:在这里你go,你可以试试这个function:
my_list = [3.5, 1.6, 2.4, 5.6, 8.9]
def select_top(a,array):
new_list = []
extra_list = []
for i in range(len(my_list)):
extra_list.append(my_list[i])
final_list = []
for i in range(a):
new_list.append(extra_list.index(max(extra_list)))
extra_list.pop(extra_list.index(max(extra_list)))
new_list = sorted(new_list,reverse=False)
for i in new_list:
final_list.append(array[i])
return final_list
print(select_top(3,my_list))
I believe it is far from optimal, but you can tweak it as much as you want to get the k top numbers and have them returned in their original order.我相信它远非最佳,但您可以尽可能多地调整它以获得前 k 个数字并让它们按原始顺序返回。 Output: Output:
[3.5, 5.6, 8.9]
How about this?这个怎么样?
[m for m in my_list if m in sorted(my_list)[-3:]]
You're building a new list of 'm' items, from the top 3 items.您正在从前 3 个项目中构建一个新的“m”项目列表。 The list comprehension keeps your items in order.列表理解使您的项目井井有条。
The order of your example is such that you could just sort it and take the 3 top items, but I think you mean that you might have the top 3 items NOT in order, like:您的示例的顺序是这样的,您可以对其进行排序并获取前 3 个项目,但我认为您的意思是您可能没有按顺序排列前 3 个项目,例如:
my_list = [3.5, 1.2, 0.3, 7.8, 3.3]
which results in这导致
[3.5,7.8,3.3]
Here's my own answer, it works for the problem.这是我自己的答案,它可以解决问题。
my_list = [3.5, 1.6, 2.4, 8.9, 5.6]
top_k = sorted(my_list)[-3:]
result = list(filter(lambda x : x in top_k,my_list))
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.