Python实现按相同基础元素分组创建子列表
Hey there! Nice start with extracting the common prefix (the part before /)—that’s exactly the right direction to solve this problem. Let’s build on that to get your desired output.
Approach
The core idea is to:
- Split each element in your list at the
/to isolate the shared prefix (likeAKS,SBHS). - Use a dictionary to map each prefix to a list of elements that share it.
- Convert the dictionary’s values into the final list of sublists you want.
Solution Code
Here’s a straightforward implementation that does this:
listRaw = ['AKS/STB', 'SBHS/AME', 'SBJ/OAK', 'SBJ/ALS', 'AKS/OSMX', 'SBHS/ABNX', 'AKS/AKX'] # Initialize a dictionary to hold our groups grouped_dict = {} for item in listRaw: # Split the item into prefix and suffix (we only care about the prefix) prefix, _ = item.split('/') # Add the item to the corresponding group in the dictionary if prefix not in grouped_dict: grouped_dict[prefix] = [] grouped_dict[prefix].append(item) # Convert the dictionary values to our desired list format desiredOutput = list(grouped_dict.values()) print(desiredOutput)
Explanation
- Splitting the item:
item.split('/')breaks each string into two parts at the/. We useprefix, _to ignore the second part since we only need the shared prefix for grouping. - Building the dictionary: We check if the prefix already exists as a key in the dictionary. If not, we create a new empty list for it. Then we add the current item to that list.
- Final formatting:
list(grouped_dict.values())takes all the grouped lists from the dictionary and turns them into a single list of sublists—perfectly matching yourdesiredOutput.
Bonus: Cleaner Version with collections.defaultdict
If you want to simplify the code even more, you can use defaultdict from Python’s collections module. It automatically creates an empty list for new keys, so you don’t need the if check:
from collections import defaultdict listRaw = ['AKS/STB', 'SBHS/AME', 'SBJ/OAK', 'SBJ/ALS', 'AKS/OSMX', 'SBHS/ABNX', 'AKS/AKX'] grouped_dict = defaultdict(list) for item in listRaw: prefix, _ = item.split('/') grouped_dict[prefix].append(item) desiredOutput = list(grouped_dict.values()) print(desiredOutput)
Both versions will output exactly what you’re looking for:
[['AKS/STB', 'AKS/OSMX', 'AKS/AKX'], ['SBHS/AME', 'SBHS/ABNX'], ['SBJ/OAK', 'SBJ/ALS']]
Hope this makes sense and helps you out! Feel free to ask if you want to dive deeper into any part of the code.
内容的提问来源于stack exchange,提问作者baptdub

