如何用Python按自定义规则对语言能力数组排序?
Got it, let's tackle this sorting problem step by step. Your goal is to sort the language list first by proficiency level (from highest to lowest), and then alphabetically by language name when proficiency levels are the same. Here's how to do it cleanly in Python:
Step 1: Define Proficiency Priority
First, we need a way to map each proficiency level to a numerical value so we can compare their hierarchy. Let's assign higher numbers to more advanced levels—this makes sorting by "higher skill first" straightforward:
proficiency_rank = {'bilingual': 3, 'advanced': 2, 'intermediate': 1}
Step 2: Use sorted() with a Custom Key
Python's built-in sorted() function lets us define a custom sorting key to match your exact requirements. We'll split each string to extract the language name and proficiency level, then sort based on two nested criteria:
- Descending proficiency: We use the negative of the rank value so higher levels appear first.
- Ascending alphabetical order: For entries with the same proficiency, we sort by the language name from A-Z.
Here's the full working code:
language = ['german : bilingual', 'english : advanced', 'dutch : intermediate', 'french : bilingual'] # Define the hierarchy of proficiency levels proficiency_rank = {'bilingual': 3, 'advanced': 2, 'intermediate': 1} # Sort the list with our custom rules sorted_languages = sorted( language, key=lambda entry: ( -proficiency_rank[entry.split(': ')[1].strip()], # Primary sort: proficiency descending entry.split(': ')[0].strip() # Secondary sort: language name ascending ) ) print(sorted_languages) # Output: ['french : bilingual', 'german : bilingual', 'english : advanced', 'dutch : intermediate']
How It Breaks Down
entry.split(': ')splits each string into two parts (e.g.,'french : bilingual'becomes['french', 'bilingual']).- The
strip()method cleans up any accidental extra spaces (a safe practice even if your input looks consistent). - The key tuple
(-rank, language_name)tellssorted()to first prioritize the negative rank (so higher proficiency comes first), then fall back to alphabetical order when ranks are identical.
Bonus: Scalability
If you ever add more proficiency levels (like 'beginner'), just update the proficiency_rank dictionary with the new level and its corresponding rank—no need to tweak the sorting logic itself!
内容的提问来源于stack exchange,提问作者tristan19954

