如何在python中找到字典值的百分位数

2024-09-28 23:38:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我被问到以下问题,并被要求不要使用纽比和熊猫。在

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

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

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

从上面两个列表中,Student[0]得到{},Student[1]得到{}等等。在

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

  • 按分数的降序排列,谁获得了前5名
  • 他至少有5个等级,按分数的递增顺序排列
  • 得分在25%到75%之间,按分数的递增顺序排列。在

对于前两个问题,我创建了两个列表的字典,以学生为键,标记为值,然后根据值升序和降序排序,但是,我得到了整个升序和降序列表,如何限制我的前5个结果(如mysql lol中的limit 5)

另外,我不知道如何解决第三个问题,你能帮帮我吗?在

请在下面找到我的代码

^{pr2}$

Tags: 列表student学生分数班级升序students降序
3条回答

要限制为5个,请添加[:5]以仅在sorted列表的前5个元素上进行交互。在

for key, value in sorted(dictionary.items(), key=lambda item: item[1],reverse=True)[:5]:应该为降序列表做工作。在

关于百分位数,这是一个统计问题,但你可以:

n = len(marks)
first_quartile = int(n/4) if (n/4).is_integer() else int(n/4) + 1
third_quartile = int(3*n/4) # as we want <75th percentile

然后在这两个值之间显示排序的(dictionary.items(), key=lambda item: item[1])的值:

sorted(dictionary.items(), key=lambda item: item[1])[first_quartile:third_quartile]

试试这个,不要使用与代码类似的numpy。在

for key, value in sorted(dictionary.items(), key=lambda item: item[1]):
      percentage = value * 100.0 / 100  # I assumed 100 as total marks (You can change it if you want like sum(Marks))
      if 25 < percentage < 75 :
            print("%s: %s : %d" % (key, value, percentage))

输出

^{pr2}$
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/

相关问题 更多 >