Python:如何根据布尔变量反转列表成员检查?

Python: how to invert list membership check based on boolean variable?

如何根据布尔变量反转列表成员资格检查?

我正在寻找一种方法来简化以下代码:

#  variables: `is_allowed:boolean`, `action:string` and `allowed_actions:list of strings`

if is_allowed:
    if action not in allowed_actions:
        print(r'{action} must be allowed!')

else:
    if action in allowed_actions:
        print(r'{action} must NOT be allowed!')

我觉得一定有办法避免检查两次,一次是 in,另一次是 not in,但想不出更简单的方法。

鉴于您的特定代码的结构方式,我认为您可以做的唯一改进就是将 action in allowed_actions 存储在一个变量中:

present = action in allowed_actions
if is_allowed:
    if not present:
        print(r'{action} must be allowed!')

else:
    if present:
        print(r'{action} must NOT be allowed!')

将测试结果与 is_allowed 进行比较。然后用is_allowed拼出正确的错误信息。

if (action in allowed_actions) != is_allowed:
    print(action, "must" if is_allowed else "must NOT", "be allowed!")