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

如何用Python将含数字区间的列表按升序排列?

Solution for Sorting Your Range/String List

Got it, I see where you're stuck. Your current code extracts the starting numbers and sorts them, but you lose the connection to the original list elements. Here's how to fix this while keeping your original items intact:

The Fix

Use Python's sorted() function with a custom key parameter. This lets you define how the sorting should be determined, without modifying the original elements themselves:

case = ['1', '5-10', '12', '18', '23', '100-110', '16-17', '20']
sorted_case = sorted(case, key=lambda x: int(x.split('-')[0]))
print(sorted_case)

What This Does

  • The lambda x: int(x.split('-')[0]) part acts as the sorting key:
    1. For each element x in the list, split it at the first - (since some items don't have a dash, split('-') will just return a single-element list)
    2. Convert that first part to an integer (so we sort numerically, not lexicographically)
  • sorted() uses this integer key to arrange the original list elements in ascending order, keeping the original strings intact.

Output

Running this code will give you exactly the sorted list you want:

['1', '5-10', '12', '16-17', '18', '20', '23', '100-110']

Why Your Original Code Didn't Work

Your approach separated the starting numbers from their parent elements, so after sorting the numbers, there was no way to map them back to the original strings. Using the key parameter keeps the elements paired with their sorting criteria, which is the cleaner, more Pythonic way to handle this.

内容的提问来源于stack exchange,提问作者Maddela Tejaswini4029

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:37:46