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

后端 未结 2 820
抹茶落季
抹茶落季 2021-01-22 17:21

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+\',         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 17:47

    No.

    modmap = {
      '-': 0,
      '': 1,
      '+': 2
    }
    
    print(sorted(grades, key=lambda x: (-ord(x[0]), modmap[x[1:]])))
    

提交回复
热议问题