检查单词列表中单词的子字符串匹配
我想检查一个单词是否在单词列表中。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以这样做:
它检查每个单词是否匹配,如果有匹配则返回 true
You could do:
It checks each word for a match and returns true if any are matches
in
按完全匹配的预期工作:您还可以使用:
或
但是,如果您正在查找子字符串,则:
btw ,不要使用
list
作为变量的名称in
is working as expected for an exact match:You can also use:
or
However, if you are looking for a substring, then:
btw, dont use
list
for the name of a variable您还可以通过将 word_list 中的所有单词连接成单个字符串来创建单个搜索字符串:
然后一个简单的
in
测试即可完成这项工作:You could also create a single search string by concatenating all of the words in word_list into a single string:
Then a simple
in
test will do the job: