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

Logical operatin in python: Value 1 or Value 2 not in list

为什么 thins 不起作用:

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-交集的值列表的另一种解决方案,仅当您需要速度或列表很长时才使用下一个解决方案,否则更喜欢使用 all() 的先前解决方案,因为更多 readable/understandable:

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()

因为“update”是真实的,它总是评估usage

你的意思大概是

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