检查单词列表中单词的子字符串匹配

Fla*_*ake 3 python substring string-matching

我想检查单词列表中是否有单词.

word = "with"
word_list = ["without", "bla", "foo", "bar"]
Run Code Online (Sandbox Code Playgroud)

我试过了if word in set(list),但由于事实in是匹配字符串而不是项目,所以不会产生想要的结果.也就是说,"with"在任何一个词中都是匹配word_list但仍然if "with" in set(list)会说True.

执行此检查的简单方法是什么,而不是手动迭代list

Win*_*ert 9

你可以这样做:

found = any(word in item for item in wordlist)
Run Code Online (Sandbox Code Playgroud)

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

  • 如果在第一次匹配后立即返回(短路)匹配,则不检查*each*字. (3认同)