多次使用“或”或“和”时是否有捷径?

乘风 python 351

原文标题Is there a shortcut when using multiple time “or” or maybe “and”?

string="abcd123"
if "a" or "b" or "c" in string:
    print("Yes")

是否有不多次输入“或”的快捷方式?

原文链接:https://stackoverflow.com//questions/71686196/is-there-a-shortcut-when-using-multiple-time-or-or-maybe-and

回复

我来回复
  • ShadowRanger的头像
    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年前 0条评论