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

发布于 2024-12-18 03:21:30 字数 373 浏览 1 评论 0原文

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

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

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

与手动迭代 list 相比,执行此检查更简单的方法是什么?

I want to check if a word is in a list of words.

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

I tried if word in set(list), but it is not yielding the wanted result due to the fact in is matching string rather than item. That is to say, "with" is a match in any of the words in the word_list but still if "with" in set(list) will say True.

What is a simpler way for doing this check than manually iterate over the list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

好菇凉咱不稀罕他 2024-12-25 03:21:30

你可以这样做:

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

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

You could do:

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

It checks each word for a match and returns true if any are matches

熊抱啵儿 2024-12-25 03:21:30

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

btw ,不要使用 list 作为变量的名称

in is working as expected for an exact match:

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

You can also use:

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

or

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

However, if you are looking for a substring, then:

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

btw, dont use list for the name of a variable

夏末染殇 2024-12-25 03:21:30

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

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

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

return word in word_list 

You could also create a single search string by concatenating all of the words in word_list into a single string:

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

Then a simple in test will do the job:

return word in word_list 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文