字母等级"D","C-",...,"A +"的Pythonic自定义排序? [英] Pythonic custom sort for letter grades 'D', 'C-' ,..., 'A+'?
本文介绍了字母等级"D","C-",...,"A +"的Pythonic自定义排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有比这更复杂的Pythonic,紧凑,直观的方式来对字母等级进行排序(不使用自定义字典)?
Is there a more Pythonic, compact, intuitive way to sort letter-grades than this (without using a custom dict)?
grades = ['B-','C','B','C+','A','D+','B+','C-','A+','D','A-']
sorted(grades, key=lambda g: (g[0], '+ -'.index((g+' ')[1])) )
['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D']
为了获得'X-','X','X +'的比较数字顺序,我做了一个空格''的hacky追加,以便 g [1]
始终存在,因此我可以使用 .index()
来获取修饰符'+-'的排名.
In order to get the comparative numerical order of 'X-','X','X+', I do a hacky append of a space ' ' so that g[1]
always exists, so then I can use .index()
to get the rank of the modifier '+ -'.
(由此问题所激励)
推荐答案
否.
modmap = {
'-': 0,
'': 1,
'+': 2
}
print(sorted(grades, key=lambda x: (-ord(x[0]), modmap[x[1:]])))
这篇关于字母等级"D","C-",...,"A +"的Pythonic自定义排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文