问题
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