tom*_*tom 73 python if-statement substring python-3.x
检查字符串x
是否为子串的Pythonic方法y
是:
if x in y:
Run Code Online (Sandbox Code Playgroud)
如果找到x
就相当于a
,b
,c
,d
,e
,f
或g
也是Python的:
if x in [a,b,c,d,e,f,g]:
Run Code Online (Sandbox Code Playgroud)
但是,如果检查一些字符串x
包含两种a
,b
,c
,d
,e
,f
或g
看起来笨重:
if a in x or b in x or c in x or d in x or e in x or f in x or g in x
Run Code Online (Sandbox Code Playgroud)
是否有更多Pythonic方法检查字符串是否x
包含列表元素?
我知道使用循环或使用正则表达式自己写这个是微不足道的:
re.search('(dog|cat|bird|mouse|elephant|pig|cow)', x)
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有一种更清洁的方式不涉及正则表达式.
ars*_*jii 119
Pythonic的方法是使用any()
:
if any(s in x for s in (a,b,c,d,e,f,g)):
Run Code Online (Sandbox Code Playgroud)
从链接的文档:
any
(可迭代的)如果iterable的任何元素为true,则返回True .如果iterable为空,则返回False.相当于:
Run Code Online (Sandbox Code Playgroud)def any(iterable): for element in iterable: if element: return True return False
另外,请注意我在这里使用了元组而不是列表.如果您的a
- g
值是预定义的,那么确实首选元组.请参阅:元组是否比Python中的列表更有效?
jwo*_*der 26
if any(q in x for q in [a,b,c,d,e,f,g]):
Run Code Online (Sandbox Code Playgroud)
我认为这就像你可以得到的短和Pythonic一样.
Sna*_*fee 10
派对有点晚了,但是
not frozenset(x).isdisjoint(frozenset(y))
Run Code Online (Sandbox Code Playgroud)
会工作,并且可能更快(在算法上,但可能不适用于较小的测试用例).