在一个字符串元组中,检查是否存在多个子字符串,最优雅的方式是什么?
tuple = ('first-second', 'second-third', 'third-first')
substr1 = 'first'
substr2 = 'second'
substr3 = 'third'
#if substr1 in tuple and substr2 in tuple and substr3 in tuple:
# should return True
在一个字符串元组中,检查是否存在多个子字符串,最优雅的方式是什么?
tuple = ('first-second', 'second-third', 'third-first')
substr1 = 'first'
substr2 = 'second'
substr3 = 'third'
#if substr1 in tuple and substr2 in tuple and substr3 in tuple:
# should return True
any(substr in str_ for str_ in tuple_)
all()
。any(substr1 in str for str in tuple_) and any(substr2 in str for str in tuple_) and any(substr3 in str for str in tuple_)
是做这件事的首选方式吗? - John Albastr
没那么糟糕,因为它只限于那个小的简单生成器。(不过我仍然不会这样做。) - Stefan Pochmann您需要针对每个子字符串迭代元组,因此可以使用 any
和 all
:
all(any(substr in s for s in data) for substr in ['first', 'second', 'third'])