python - 你如何找到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名,按分数降序排列
- 谁获得了至少 5 个等级,按分数升序排列
- 谁的分数在 >25th 百分位 <75th 百分位之间,分数升序排列。
对于前两个问题,我创建了一个包含学生作为键和标记作为值的列表的字典,然后根据值对升序和降序进行排序,但是,我得到了整个升序和降序列表,如何我限制了我的前 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)
解决方案
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/
推荐阅读
- angular - Add ionic 4 icon to ng select dropdown menu
- google-cloud-platform - 公开文件的安全读取 URL
- ios - 同时处理两个手势识别器
- c# - 我应该如何使用 P/Invoke 将字符串数组传递给 C 库?
- sql-server - Azure SQL 单数据库 DTU 超时已过期错误
- angular - 如何呈现“浮动”消息?
- pandas - Pandas Dataframe - 更新没有循环的动态行和列
- database - 如何设置 CouchDB 附件存储为文件而不是映射到数据库中
- python - 为什么 AttributeError: 'str' object has no attribute 'decode' 在 decode 是字符串时发生?
- javascript - 父 React 组件未使用反应钩子在子级更改状态时重新渲染;