简体   繁体   English

select n 基于排名列表的 python 列表中排名靠前的名称

[英]select n top ranked names from a python list based on a rank-list

I have a sorted python list of ranks and a corresponding list of names.我有一个排序的 python 等级列表和相应的名称列表。 How do I get all the top 5 names in the order of the rank from the python list rank?如何从 python 列表排名中按排名顺序获得所有前 5 个名称?

rank: [ 2, 1, 4, 1, 1, 3, 1]
names:  ['X', 'Y', 'Z', 'A', 'B', 'C', 'D']

desired output:所需的 output:

['X', 'Y', 'A', 'B', 'D']

I got this.. but does not limit to top 5我得到了这个..但不限于前5名

[ j for (i,j) in zip(rank, names) if i <= 2 ]

You can use sorted with zip :您可以使用zip sorted

In [244]: [x for _, x in sorted(zip(rank, names))][:5]
Out[244]: ['A', 'B', 'D', 'Y', 'X']

You need to sort twice to get the required result (Itemgtter is to extract the value at index 0)-您需要排序两次才能获得所需的结果(Itemgtter 是提取索引 0 处的值)-

from operator import itemgetter
result = list(map(itemgetter(0),sorted(sorted(zip(names,rank),key=lambda x:x[1])[:5],key=lambda x:x[1],reverse=True)))
print(result ) # ['X', 'Y', 'A', 'B', 'D']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM