【问题标题】:How to avoid strings containing parts of a search string from appearing when using the 'in' operator?使用“in”运算符时如何避免出现包含部分搜索字符串的字符串?
【发布时间】:2018-08-08 22:44:13
【问题描述】:

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

例如,我希望所有包含'kmt2d' 的列表都返回True。但是,包含'set2d' 的列表也会返回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]

我的代码有问题还是有其他运算符可以帮助我获得相同的结果?

【问题讨论】:

  • minimal reproducible example 请。您发布的代码没有运行,即使它运行它也不会产生您声称它产生的输出。此外,您似乎想要进行平等检查(即==),而不是成员资格测试(in)。
  • 如果您想找到完全匹配,请在 if 条件中使用 ==(相等)运算符。 (将if k in i 更改为if k == i
  • 我更正了您的语法并将 listthree 初始化移动到 for 循环之前 - 这是让它累积三个值所必需的。然后程序按您的意愿运行。我没有看到一个简单的更改可以让您当前的代码产生您声称的输出。

标签: python string python-3.x list operators


【解决方案1】:

尝试以下方法:

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 来测试该项目是否出现在列表中,而无需实际扫描字符串本身。

【讨论】:

    【解决方案2】:

    这段代码运行良好:

    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]
    

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 2021-06-12
      • 2011-05-25
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多