【问题标题】:How to simplify multiple conditions in Python如何在 Python 中简化多个条件
【发布时间】:2013-12-25 22:03:05
【问题描述】:

我用python写了一个解析一些字符串的脚本。

问题是我需要检查字符串是否包含某些部分。 我发现的方式不够聪明。

这是我的代码:

if ("CondA" not in message) or ("CondB" not in message) or ("CondC" not in message) or ...:

有没有办法优化这个?对于这种情况,我还有 6 项其他检查。

【问题讨论】:

    标签: python multiple-conditions


    【解决方案1】:

    使用带有any()all() 的生成器:

    if any(c not in message for c in ('CondA', 'CondB', ...)):
        ...
    

    在 Python 3 中,您还可以利用 map() 的懒惰:

    if not all(map(message.__contains__, ('CondA', 'CondB', ...))):
    

    【讨论】:

      【解决方案2】:

      你可以使用any函数:

      if any(c not in message for c in ("CondA", "CondB", "CondC")):
          ...
      

      【讨论】:

      • 我可以在循环中使用列表吗?例如:for c in list
      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 2022-12-21
      • 2022-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多