Pythonic custom sort for letter grades 'D', 'C-' ,…, 'A+'?

不羁岁月 提交于 2020-01-30 08:29:04

问题


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']

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 '+ -'.

(Motivated by this question)


回答1:


No.

modmap = {
  '-': 0,
  '': 1,
  '+': 2
}

print(sorted(grades, key=lambda x: (-ord(x[0]), modmap[x[1:]])))


来源:https://stackoverflow.com/questions/50111642/pythonic-custom-sort-for-letter-grades-d-c-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!