首页 > 解决方案 > 你如何找到python中字典值的百分位数

问题描述

我收到了以下问题,并被要求不要使用 numpy 和 pandas。

考虑两个列表中给出的班级学生的分数列表

Students =['student1','student2','student3','student4','student5','student6','student7','student8','student9','student10'] 

Marks = [45, 78, 12, 14, 48, 43, 45, 98, 35, 80] 

从上面的两个列表中Student[0]得到 got Marks[0]Student[1]gotMarks[1]等等。

所以任务是打印学生的名字

对于前两个问题,我创建了一个包含学生作为键和标记作为值的列表的字典,然后根据值对升序和降序进行排序,但是,我得到了整个升序和降序列表,如何我限制了我的前 5 个结果(就像 mysql 中的 LIMIT 5 大声笑)

另外,我对如何解决第三个问题一无所知,您能帮帮我吗?

请在下面找到我的代码

Students=['student1','student2','student3','student4','student5','student6','student7','student8','student9','student10']

Marks = [45, 78, 12, 14, 48, 43, 47, 98, 35, 80]

def display_dash_board(students, marks):

    dictionary = dict(zip(Students,Marks))

    print('top_5_students')

    for key, value in sorted(dictionary.items(), key=lambda item: item[1],reverse=True):
          print("%s: %s" % (key, value))

#this is giving me the entire descending list (not python list) of all 10 students how to limit to five?


    print('least_5_students')

    for key, value in sorted(dictionary.items(), key=lambda item: item[1]):
          print("%s: %s" % (key, value))

    #this is giving me the entire ascending list (not python list) of all 10 students how to limit to five?   

    # How to go about the percentile question ?

display_dash_board(Students, Marks)

标签: python

解决方案


def percentile(N, percent, key=lambda x:x):
    """
    Find the percentile of a list of values.

    @parameter N - is a list of values. Note N MUST BE already sorted.
    @parameter percent - a float value from 0.0 to 1.0.
    @parameter key - optional key function to compute value from each element of N.

    @return - the percentile of the values
    """
    if not N:
        return None
    k = (len(N)-1) * percent
    f = math.floor(k)
    c = math.ceil(k)
    if f == c:
        return key(N[int(k)])
    d0 = key(N[int(f)]) * (c-k)
    d1 = key(N[int(c)]) * (k-f)
    return d0+d1

使用上述函数通过提供排序的标记列表来计算百分位数的值。然后根据百分位值过滤字典。

上述函数的灵感来自http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/


推荐阅读