Python嵌套列表去重:处理带后缀标识元素并生成指定输出
Solution for Processing Nested List in Python
Got it, let's break down how to transform your nested list exactly as you need it. The key tasks are: deduplicating country entries by their prefix, reformatting the fruit entries to remove the numeric suffix, and adjusting the order to match your desired output.
Full Working Code
def clean_country_entries(country_list): # Extract the base country name (before the underscore + number) and deduplicate unique_countries = set() for entry in country_list: # Split on the first underscore to get the country prefix country_name = entry.split('_')[0] unique_countries.add(country_name) # Remove reverse=True if you want alphabetical order (America first, then England) return sorted(unique_countries, reverse=True) def reformat_fruit_entries(fruit_list): # Remove the numeric segment from each fruit entry reformatted_fruits = [] for entry in fruit_list: parts = entry.split('_') # Combine the first part and the last part (skip the middle number) new_entry = f"{parts[0]}_{parts[2]}" reformatted_fruits.append(new_entry) # Sort in reverse to match your sample output's fruit order return sorted(reformatted_fruits, reverse=True) # Your original nested list original_list = [ ['country',['America_1','America_2','America_3','America_4','England_5','England_6'],['apple_1_more','orange_1_more']], ['country',['Brazil_2','Brazil_3','Brazil_1','Brazil_4','Mexico_1','Mexico_3','Mexico_2'],['grapes_1_less','banana_1_more']] ] # Process each sublist in the original list final_result = [] for sublist in original_list: tag = sublist[0] cleaned_countries = clean_country_entries(sublist[1]) reformatted_fruits = reformat_fruit_entries(sublist[2]) final_result.append([tag, cleaned_countries, reformatted_fruits]) # Print the result print(final_result)
Matching Your Desired Output
To get exactly the output you specified:
- Remove
reverse=Truefrom thesorted()call inclean_country_entries(this will return['America', 'England']for the first sublist) - Keep the
reverse=Trueinreformat_fruit_entries(this returns['orange_more', 'apple_more']for the first sublist)
The final output will be:
[['country', ['America', 'England'], ['orange_more', 'apple_more']], ['country', ['Brazil', 'Mexico'], ['grapes_less', 'banana_more']]]
How It Works
- Cleaning Country Entries: We use a set to automatically eliminate duplicates. Splitting each entry on the first underscore lets us grab the base country name (e.g.,
AmericafromAmerica_1). Sorting adjusts the order to match your sample. - Reformatting Fruit Entries: Each fruit entry is split into three parts (e.g.,
apple_1_morebecomes['apple', '1', 'more']). We skip the numeric middle part and combine the first and third parts to get the cleaned format. - Putting It All Together: We loop through each top-level sublist in your original list, apply the two cleaning functions, and assemble the final result.
内容的提问来源于stack exchange,提问作者GRNearth
相关产品推荐
相关产品推荐

