如何在香草 Python 中对列表进行排名? [英] How do I rank a list in vanilla Python?

查看:76
本文介绍了如何在香草 Python 中对列表进行排名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表:

[4, 5, 2, 1]

我需要对这些进行排名并输出:

I need to rank these and have the output as:

[3, 4, 2, 1]

如果两个案例中的排名相同:

If two have the same ranking in the case:

[4, 4, 2, 3] then the rankings should be averaged -> [3.5, 3.5, 1, 2]

编辑
这里 rank 代表数字在排序列表中的位置.如果有多个数值相同的数字,那么每个这样的数字的排名将是它们位置的平均值.

EDIT
Here rank stands for position of number in a sorted list. If there are multiple numbers with same value, then rank of each such number will be average of their positions.

推荐答案

可能不是最有效率的,但这是有效的.

Probably not the most efficient, but this works.

  • rank 接受一个已排序的列表和一个项目,并通过找到它被插入到之前所有元素的位置来确定该项目的排名等于它,after,然后平均两个位置(使用数组二等分).
  • rank_list 使用 rank 来计算所有元素的等级.partial 调用只是为了简化,不必为每个项目查找再次对列表进行排序.
  • rank takes a sorted list and an item, and figures out the rank of that item should be by finding where it would be inserted to go before all elements that are equal to it, and after, then averaging the two positions (using array bisection).
  • rank_list uses rank to figure out the ranks of all elements. The partial call is just to simplify, and not have to sort the list again for each item lookup.

像这样:

from bisect import bisect_left, bisect_right
from functools import partial

def rank(item, lst):
    '''return rank of item in sorted list'''
    return (1 + bisect_left(lst, item) + bisect_right(lst, item)) / 2.0

def rank_list(lst):
    f = partial(rank, lst=sorted(lst))
    return [f(i) for i in lst]

rank_list([4, 4, 2, 1])
## [3.5, 3.5, 2.0, 1.0]

这篇关于如何在香草 Python 中对列表进行排名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆