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

如何移除字符串列表中所有元素共有的重复子串并提取独有内容

Python实现移除列表字符串公共前缀的方案

实现逻辑

遍历所有字符串逐位比对,找到所有元素共有的最长前缀后,将每个字符串去掉该前缀即可得到独有内容,代码中额外添加了空格清理逻辑,适配示例的输出格式要求。

完整代码

def remove_common_prefix(str_list: list[str]) -> list[str]:
    # 空列表直接返回
    if not str_list:
        return []
    # 以最短字符串为基准,公共前缀不可能超过它的长度
    base_str = min(str_list, key=len)
    common_prefix_len = 0

    for idx, char in enumerate(base_str):
        # 检查所有字符串同位置字符是否一致
        all_match = True
        for s in str_list:
            if s[idx] != char:
                all_match = False
                break
        if not all_match:
            break
        common_prefix_len = idx + 1

    # 移除公共前缀并清理首尾空格
    return [s[common_prefix_len:].strip() for s in str_list]

测试验证

# 示例1测试
lst = ['State your favorite fruit: Apple', 'State your favorite fruit: Orange', 'State your favorite fruit: Grapes']
print(remove_common_prefix(lst))
# 输出:['Apple', 'Orange', 'Grapes']

# 多列表测试
lst1 = ['This is a bag', 'This is a cat', 'This is a dog']
lst2 = ['Favorite drink: Cola', 'Favorite drink: Sprite']
lst3 = ['My name is James', 'My name is Mary Jane', 'My name is Lopez']
print(remove_common_prefix(lst1)) # 输出 ['bag', 'cat', 'dog']
print(remove_common_prefix(lst2)) # 输出 ['Cola', 'Sprite']
print(remove_common_prefix(lst3)) # 输出 ['James', 'Mary Jane', 'Lopez']

如果你不需要自动清理结果首尾的空格,直接把最后一行的.strip()去掉即可。

内容的提问来源于stack exchange,提问作者Boon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:54:03