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

后端 未结 2 842
抹茶落季
抹茶落季 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.

提交回复
热议问题