检查子字符串是否在字符串列表中? [英] Check if substring is in a list of strings?
问题描述
我之前已经找到了这个问题的一些答案,但是它们对于当前的Python版本似乎已经过时了(或者至少它们对我不起作用).
I have found some answers to this question before, but they seem to be obsolete for the current Python versions (or at least they don't work for me).
我要检查字符串列表中是否包含子字符串.我只需要布尔结果.
I want to check if a substring is contained in a list of strings. I only need the boolean result.
我找到了这个解决方案:
I found this solution:
word_to_check = 'or'
wordlist = ['yellow','orange','red']
result = any(word_to_check in word for word in worldlist)
从此代码中,我希望得到一个True
值.如果单词是"der",则输出应为False
.
From this code I would expect to get a True
value. If the word was "der", then the output should be False
.
但是,结果是生成器函数,我找不到获取True
值的方法.
However, the result is a generator function, and I can't find a way to get the True
value.
有什么主意吗?
推荐答案
您可以从__builtin__
导入any
,以防被其他any
代替:
You can import any
from __builtin__
in case it was replaced by some other any
:
>>> from __builtin__ import any as b_any
>>> lst = ['yellow', 'orange', 'red']
>>> word = "or"
>>> b_any(word in x for x in lst)
True
请注意,在Python 3中,__builtin__
已重命名为builtins
.
Note that in Python 3 __builtin__
has been renamed to builtins
.
这篇关于检查子字符串是否在字符串列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!