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

后端 未结 2 813
抹茶落季
抹茶落季 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条回答
  • 2021-01-22 17:37

    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.

    0 讨论(0)
  • 2021-01-22 17:47

    No.

    modmap = {
      '-': 0,
      '': 1,
      '+': 2
    }
    
    print(sorted(grades, key=lambda x: (-ord(x[0]), modmap[x[1:]])))
    
    0 讨论(0)
提交回复
热议问题