python中的逻辑运算符:值1或值2不在列表中

问题描述

为什么变薄不起作用:

if "update" or "create" not in sys.argv:
    usage()
$ python myScript.py update
# In if

$ python myScript.py create
# In if

目标:如何检查列表中既没有“更新”也没有“创建”,然后if语句中的代码运行了?

解决方法

将代码更正为:

if "update" not in sys.argv and "create" not in sys.argv:
    usage()

如果您需要从可能的列表中检查许多值,请对all()使用下一个解决方案:

if all((s not in sys.argv) for s in ["update","create"]):
    usage()

或者是使用sets-intersection的值列表的另一种解决方案,仅当您需要速度或列表很长时才使用下一个解决方案,否则,更易读/可理解的是使用以前使用all()的解决方案:>

if len(set(["update","create"]) & set(sys.argv)) == 0:
   usage()

注意:每次调用此代码时,都会从列表中设置set(list_object)个代码构造,并花费一些时间,因此,如果该代码运行了很多次在a = set(list_a)之类的变量中构造的构造并重用了a后来很多次。

,

您的代码等同于

if "update" or ("create" not in sys.argv):
    usage()

由于“更新”是真实的,因此它将始终评估usage

您的意思可能是

if "update" not in sys.argv and "create" not in sys.argv:
    usage()