Python 2中如何按子列表第2位及以后元素类型排序嵌套列表
Got it, let's work through this sorting problem together. The core challenge here is that we need a two-tiered sorting rule: first group sublists by whether their second element (and beyond) are alphabetical or numerical, then sort within each group. Standard tools like operator.itemgetter can't handle this conditional grouping, so we'll use a custom sorting key to make it happen.
Step-by-Step Breakdown
- Group Priority Assignment: We'll assign a priority value to each sublist to control their overall order:
- Sublists with an alphabetical second element get a priority of
0(so they appear first) - Sublists with a numerical second element get a priority of
1(so they appear last)
- Sublists with an alphabetical second element get a priority of
- Intra-Group Sorting: Within each priority group, we'll sort by the first element of the sublist to match your desired output order.
Working Python 2 Code
First, let's define your input list clearly (assuming a5, abc are strings, and 4, 1 are integers):
list_of_list = [["a5", "abc", "xyz"], ["a1", "abc", "def"], ["a2", 4, 2, 3], ["a3", 1, 2]]
Now use the sorted() function with a custom lambda key:
sorted_list = sorted(list_of_list, key=lambda x: (0 if isinstance(x[1], basestring) and x[1].isalpha() else 1, x[0]))
Note: In Python 2, basestring covers both regular str and unicode strings, making the check more robust. If all your alphabetical elements are plain str, you can use isinstance(x[1], str) instead.
Why This Works
The lambda returns a tuple (group_priority, first_element):
- Tuples are compared element-by-element in Python, so all sublists with
group_priority=0will automatically come before those with1 - Within the same group, sublists are sorted lexicographically by their first element (e.g.,
"a1"comes before"a5","a3"comes before"a2"), which matches your expected output.
Test the Output
Running the code will produce exactly the sorted list you need:
print(sorted_list) # Output: [["a1", "abc", "def"], ["a5", "abc", "xyz"], ["a3", 1, 2], ["a2", 4, 2, 3]]
Edge Case Adjustment
If you have sublists where the second element is a mixed string (like "abc123"), the x[1].isalpha() check will push them to the numerical group. If you need to adjust this logic (e.g., keep any string with letters in the front group), just modify the condition in the lambda to fit your needs.
内容的提问来源于stack exchange,提问作者nad

