使用 'in' 运算符时如何避免出现包含部分搜索字符串的字符串?

How to avoid strings containing parts of a search string from appearing when using the 'in' operator?

我知道有几篇关于如何在字符串中查找子字符串的帖子,但我遇到了相反的问题。当我使用 'in' 运算符时,如何避免出现包含部分搜索字符串的字符串?

例如,我想要包含 'kmt2d' 到 return True 的所有列表。但是,包含 'set2d' 的列表也包含 return True,因为两者之间有 't2d' 公共子字符串。

这是我的代码示例:

listone = ['kmt2d']
listtwo = ['set2d', 'hgt', 'kmt2d']
listthree = []

for i in listtwo:
    for k in listone:
        if k in i:
            listthree.append(True)
        else:
            listthree.append(False) 

listthree 的输出显示为:

listthree = [True, False, True] 

但是,我希望它是:

listthree = [False, False, True]

我的代码有问题吗?或者是否有任何其他运算符可以帮助我实现相同的结果?

尝试以下操作:

one = ['kmt2d']
two = ['set2d', 'hgt', 'kmt2d']
three = [item for item in two if item in one]

# which is:
three = []
for item in two:
    if item in one:
        three.append(item)

在第二个循环中,您遍历第二个列表,这意味着 in 运算符扫描字符串,而不是它是否存在于列表中。取消第二个循环并使用 in 只是为了测试该项目是否出现在列表中而不实际扫描字符串本身。

这段代码工作正常:

listone = ['kmt2d']
listtwo = ['set2d', 'hgt', 'kmt2d']
listthree = []

for i in listtwo:
    for k in listone:
        if k in i:
            listthree.append(True)
        else:
            listthree.append(False)

输出:

listthree = [False, False, True]