Skip to main content
 首页 » 编程设计

python之检查列表中的字符串是否是同一列表中另一个字符串的子集

2024年09月07日35pander-it

我正在处理一个带有字符串列表的 python 脚本。我想创建一个接受字符串列表并返回超集列表并删除子集的方法。考虑以下情况:

A = ['this is a sentence', 'who is alice', 'sentence', 'hi i am carrot', 'i am carrot'] 

现在如果你看到数组A,它有两个元素,它们是一对超集和子集,'this is a sentence'是的超集'sentence' 和类似的 'hi i am carrot' 和 'i am carrot' 我想编写一个函数,从列表中删除子集并返回更新的列表。

在上面的示例中,输出如下所示:

ResultA = ['this is a sentence', 'who is alice', 'hi i am carrot'] 

我已经编写了一个快速代码示例,可以展示我正在寻找的内容,但我不确定使用两个 for 循环是否是正确的方法:

elements_to_keep = [] 
for i in phase_two_match: 
    for j in phase_two_match: 
        if i == j: 
            continue 
        else: 
            if j not in i: 
                elements_to_keep.append(j) 

请您参考如下方法:

这会返回 A 中不在 A 中的另一个项目的项目,但会跳过项目完全匹配的实例(即:自己跳过)

[x for x in A if not any(x in y and x!=y for y in A)] 
# returns: 
['this is a sentence', 'who is alice', 'hi i am carrot']