多次使用“或”或“和”时是否有捷径?
python 452
原文标题 :Is there a shortcut when using multiple time “or” or maybe “and”?
string="abcd123"
if "a" or "b" or "c" in string:
print("Yes")
是否有不多次输入“或”的快捷方式?
回复
我来回复-
ShadowRanger 评论
快捷方式(对于正确编写的代码
if "a" in string or "b" in string or "c" in string:
)是any
函数和生成器表达式:if any(s in string for s in ("a", "b", "c")):
它将返回
True
,只要它找到包含在string
中的值,或者False
如果没有找到;要搜索更多值,只需将它们添加到内联tuple
。如果你需要知道哪个值,你可以使用next
和一个过滤的genexpr来达到类似的最终结果:found_item = next((s for s in ("a", "b", "c") if s in string), None) # Returns first item found or None if found_item is not None: # Process found_item; it will be "a", "b" or "c", whichever was found first
2年前