如何按首尾衔接规则排序嵌套列表:以含0元素子列表开头
Solution to Nested List Chaining
Alright, let's solve this problem exactly as you described. The goal is to chain your nested lists so that:
- We start with the sublist containing
0 - Each subsequent sublist starts with the last element of the previous one
- Every sublist keeps its original internal order
Here's a Python implementation that gets the job done:
my_list = [[9, 10, 1], [1, 7, 5, 6, 11], [0, 4], [4, 2, 9]] result = [] # Make a copy of the original list to avoid modifying it directly remaining_sublists = my_list.copy() # Step 1: Grab the starting sublist (the one with 0) starting_sublist = next(sublist for sublist in remaining_sublists if 0 in sublist) result.append(starting_sublist) remaining_sublists.remove(starting_sublist) # Step 2: Chain the rest of the sublists while remaining_sublists: # Get the last element of the most recently added sublist last_item = result[-1][-1] # Find the next sublist that starts with this last item next_sublist = next(sublist for sublist in remaining_sublists if sublist[0] == last_item) result.append(next_sublist) remaining_sublists.remove(next_sublist) print(result) # Output: [[0, 4], [4, 2, 9], [9, 10, 1], [1, 7, 5, 6, 11]]
How this works:
- We first make a copy of your original list so we don't alter the original data while we work.
- We use
next()to quickly find the sublist containing0—this becomes our starting point, which we add to the result and remove from the remaining list. - Then we loop: we check the last element of the last sublist in our result, find the first remaining sublist that starts with that element, add it to the result, and remove it from the remaining pool. We keep doing this until all sublists are used.
A quick note on edge cases:
This code assumes your input will always have exactly one sublist with 0, and there's a perfect chain of matching sublists. If there's a chance these conditions might not hold (like missing the 0-sublist or no matching next sublist), wrap the next() calls in a try-except StopIteration block to handle those errors gracefully.
内容的提问来源于stack exchange,提问作者bhawesh sah
相关产品推荐
相关产品推荐

