You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python按自定义规则对语言能力数组排序?

How to Sort Language Proficiency Entries in 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:

  1. Descending proficiency: We use the negative of the rank value so higher levels appear first.
  2. 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) tells sorted() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:47:55