【问题标题】:Check substring match of a word in a list of words检查单词列表中单词的子字符串匹配
【发布时间】:2011-11-26 00:31:20
【问题描述】:

我想检查一个单词是否在单词列表中。

word = "with"
word_list = ["without", "bla", "foo", "bar"]

我尝试了if word in set(list),但由于in 匹配的是字符串而不是项目,因此它没有产生想要的结果。也就是说,"with" 匹配 word_list 中的任何单词,但 if "with" in set(list) 仍然会说 True

有什么比手动遍历list 更简单的方法来执行此检查?

【问题讨论】:

  • 那你想要什么结果?
  • 您真的使用名称list 来存储该列表,还是只是为了说明?它是内置的,所以你应该避免使用会掩盖它的名称。
  • 好点布莱恩!在任何情况下,最好避免覆盖列表关键字
  • ... 但是根据程序员通常认为有用的定义,"with" 不在该列表中
  • 哦,是的,我想我现在得到了问题的表述。

标签: python substring string-matching


【解决方案1】:

你可以这样做:

found = any(word in item for item in wordlist)

它检查每个单词是否匹配,如果匹配则返回 true

【讨论】:

  • 好吧,现在不用怀疑了。这是一个绝妙的解决方案!
  • 它不会检查 每个 单词是否有匹配,它会在第一次匹配后立即返回(短路)。
  • 确实如此。对我来说,不清楚他是在寻找布尔结果还是完整的匹配列表。
【解决方案2】:

in完全匹配中按预期工作:

>>> word = "with"
>>> mylist = ["without", "bla", "foo", "bar"]
>>> word in mylist
False
>>> 

你也可以使用:

milist.index(myword)  # gives error if your word is not in the list (use in a try/except)

milist.count(myword)  # gives a number > 0 if the word is in the list.

但是,如果您正在寻找 子字符串,那么:

for item in mylist:
    if word in item:     
        print 'found'
        break

顺便说一句,变量名不要使用list

【讨论】:

    【解决方案3】:

    您还可以通过将 word_list 中的所有单词连接成单个字符串来创建单个搜索字符串:

    word = "with" 
    word_list = ' '.join(["without", "bla", "foo", "bar"])
    

    然后一个简单的in 测试就可以完成这项工作:

    return word in word_list 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2021-10-23
      • 1970-01-01
      相关资源
      最近更新 更多