如何用Python将含数字区间的列表按升序排列?
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:- For each element
xin the list, split it at the first-(since some items don't have a dash,split('-')will just return a single-element list) - Convert that first part to an integer (so we sort numerically, not lexicographically)
- For each element
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

