You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现按相同基础元素分组创建子列表

Grouping List Elements by Common Prefix in 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:

  1. Split each element in your list at the / to isolate the shared prefix (like AKS, SBHS).
  2. Use a dictionary to map each prefix to a list of elements that share it.
  3. 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 use prefix, _ 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 your desiredOutput.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:30:22