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+\',
Yes-ish?
>>> sorted(grades, key=lambda g: g + ',')
['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D']
Clearly more compact, and I'd say also pythonic, just not very intuitive :-P
Works because '+' < ',' < '-'
.
Another one:
>>> sorted(grades, key=lambda g: (g[0], ' -'.find(g[1:])))
['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D']
Suffix +
won't be found in ' -'
, so find
returns -1
. Empty suffix results in 0
, and suffix -
results in 1
.
No.
modmap = {
'-': 0,
'': 1,
'+': 2
}
print(sorted(grades, key=lambda x: (-ord(x[0]), modmap[x[1:]])))