Python3列表排序请求:按指定规则排序特定字符串序列
Python 3: Custom Sorting for Alphanumeric Strings with Apostrophes
Got it, let's tackle this custom sorting task. Looking at your original list and target result, the sorting rules we need to implement are:
- Group by the middle code (the part between
01104D-and the final number, likeBB,CC, etc.) - Within each group:
- First sort all entries without an apostrophe (
') in the suffix - Then sort entries with an apostrophe
- For the numeric suffixes (like
2,12,102), we need natural numeric sorting (not lexicographical, so2comes before12, which comes before102)
- First sort all entries without an apostrophe (
Here's a Python 3 implementation that does exactly this:
original_list = [ "01104D-BB'42", "01104D-BB42", "01104D-BB43", "01104D-CC'42", "01104D-CC'72", "01104D-CC32", "01104D-CC42", "01104D-CC62", "01104D-CC72", "01104D-DD'74", "01104D-DD'75", "01104D-DD'76", "01104D-DD'77", "01104D-DD'78", "01104D-DD75", "01104D-DD76", "01104D-DD77", "01104D-DD78", "01104D-EE'102", "01104D-EE'12", "01104D-EE'2", "01104D-EE'32", "01104D-EE'42", "01104D-EE'52", "01104D-EE'53", "01104D-EE'72", "01104D-EE'82", "01104D-EE'92", "01104D-EE102", "01104D-EE12", "01104D-EE2", "01104D-EE3", "01104D-EE32", "01104D-EE42", "01104D-EE52", "01104D-EE62", "01104D-EE72", "01104D-EE82", "01104D-EE83", "01104D-EE92", "01104D-EE93" ] def sort_key(s): # Split the string into prefix and the rest of the content prefix_part, rest = s.split('-', 1) # Handle entries with apostrophe if "'" in rest: middle_code, suffix = rest.split("'", 1) has_apostrophe = 1 # Flag to sort these after non-apostrophe entries else: # Use regex to split letters and digits for non-apostrophe entries import re match = re.match(r"([A-Z]+)(\d+)", rest) middle_code = match.group(1) suffix = match.group(2) has_apostrophe = 0 # Return a tuple that defines the sort order return (middle_code, has_apostrophe, int(suffix)) # Sort the list using our custom key sorted_list = sorted(original_list, key=sort_key) # Print the sorted result to verify for item in sorted_list: print(item)
How this works:
- The
sort_keyfunction generates a comparison tuple that Python uses to order entries:- First element: The middle code (e.g.,
BB,CC) sorts groups alphabetically. - Second element: A flag (
0for no apostrophe,1for apostrophe) ensures non-apostrophe entries come first in each group. - Third element: The numeric suffix converted to an integer, so sorting uses numeric order instead of lexicographical (fixes the
2vs12vs102ordering problem).
- First element: The middle code (e.g.,
- Regex helps cleanly split non-apostrophe entries into letter codes and numeric suffixes, even for edge cases like
EE3orEE102.
Running this code will output exactly the target sorted list you provided.
内容的提问来源于stack exchange,提问作者Pydavide
相关产品推荐
相关产品推荐

