Python 是否有一种更简洁的方式来表达“如果 x 包含一个 | b | c | d...”?

检查字符串 x是否是 y的子字符串的 Python 方法是:

if x in y:

找出 x是否等同于 abcdefg也是 Python 式的:

if x in [a,b,c,d,e,f,g]:

但是,检查一些字符串 x是否包含 abcdefg似乎有些笨拙:

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

是否有更多的 蟒蛇方法来检查字符串 x是否包含列表的元素?

我知道自己使用循环或正则表达式编写这些代码很简单:

re.search('(dog|cat|bird|mouse|elephant|pig|cow)', x)

但我想知道是否有一个更干净的方法,不涉及正则表达式。

26343 次浏览

The Pythonic approach would be to use any():

if any(s in x for s in (a,b,c,d,e,f,g)):

From the linked documentation:

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
for element in iterable:
if element:
return True
return False

Also, notice that I've used a tuple instead of a list here. If your a-g values are pre-defined, then a tuple would indeed be preferred. See: Are tuples more efficient than lists in Python?

if any(q in x for q in [a,b,c,d,e,f,g]):

I think that's about as short & Pythonic as you can get it.

without using any but simply max

def is_in(symbol, lst):
return max([symbol in x for x in lst])


print is_in('a',['ae','br','tl'])
print is_in('c',['ae','br','tl'])

gives

>>>
True
False

A bit late to the party, but

not frozenset(x).isdisjoint(frozenset(y))

would work, and may be faster (algorithmically, but maybe not for smaller test cases).