如何用更Pythonic的方式排序字母成绩(不使用自定义字典)?
Great question! Your current approach works, but we can make the sorting logic more readable and intuitive while keeping it Pythonic—no custom dictionaries required. Here are a few clean, idiomatic options:
Option 1: Explicit Ternary Priority Mapping
This approach directly maps each grade suffix to a priority value that enforces the X+ > X > X- order. The lambda makes the logic immediately clear to anyone reading the code:
grades = ['B-','C','B','C+','A','D+','B+','C-','A+','D','A-'] sorted_grades = sorted(grades, key=lambda g: ( g[0], # First sort by the main letter (A < B < C < D) -1 if '+' in g else 1 if '-' in g else 0 # Then sort suffixes: + (highest) > plain > - (lowest) ))
Running this gives exactly the desired output:
['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D']
The priority values (-1, 0, 1) work because Python sorts numbers in ascending order—so within the same main letter, + grades (priority -1) come first, followed by plain grades (0), then - grades (1).
Option 2: Simplified String Padding with Priority String
If you prefer to stick with the string index approach but make it cleaner, use str.ljust() instead of concatenating a space explicitly. This makes the intent of padding the grade to 2 characters obvious at a glance:
sorted_grades = sorted(grades, key=lambda g: (g[0], '+ -'.index(g.ljust(2)[1])))
g.ljust(2) ensures every grade is at least 2 characters long (adding a space to plain grades like 'A'), so g.ljust(2)[1] reliably grabs the suffix (or space). The '+ -' string defines priority order: '+' is index 0, space is index 1, '-' is index 2—sorting by this index gives the correct sequence.
Why These Are More Pythonic
- Readability: Both options make the sorting logic explicit, unlike the original
(g+' ')[1]which requires a moment of parsing to understand. - Conciseness: No extra helper functions or data structures needed—just a straightforward lambda that fits neatly in one line (or split for readability).
- Idiomatic: Leverages Python's built-in tuple sorting and simple conditional logic, patterns that are widely recognized in the Python community.
内容的提问来源于stack exchange,提问作者smci

