如何用Python优雅计算百分位数对应的十分位数(D01-D10)
优雅计算百分位数对应的十分位数(Python风格)
需求说明
已知输入是取值范围为0-100的浮点型百分位数,需要编写符合Python风格的代码,计算出对应的十分位数(格式为D01到D10)。现有如下四分位数计算函数作为参考,希望避免编写10个if-else条件:
def quartile(percentile): p = 100 - percentile if p <= 25: return 'Q1' elif p <= 50: return 'Q2' elif p <= 75: return 'Q3' else: return 'Q4'
预期输出示例:
>>> decile(95.5) 'D01' >>> decile(8.3) 'D10'
解决方案
利用数学计算结合字符串格式化,可通过简洁逻辑完成需求,完全避免多分支判断:
import math def decile(percentile): decile_number = math.ceil((100 - percentile) / 10) return f'D{decile_number:02d}'
逻辑解释
- 沿用四分位数函数的反向转换逻辑:计算
100 - percentile,将百分位数映射为0到100的反向数值 - 将反向数值除以10后向上取整,得到1到10的十分位数编号(比如4.5→1,91.7→10)
- 通过f-string格式化输出为两位数字的
Dxx格式,确保1显示为D01,10显示为D10
验证示例
运行测试代码:
print(decile(95.5)) # 输出 'D01' print(decile(8.3)) # 输出 'D10' print(decile(50)) # 输出 'D05' print(decile(0)) # 输出 'D10' print(decile(100)) # 输出 'D01'
内容的提问来源于stack exchange,提问作者BoB
相关产品推荐
相关产品推荐

