我有一个python脚本,它可以接收零个或三个命令行参数。(它要么以默认行为运行,要么需要指定所有三个值。)
对于这样的东西,理想的语法是什么:
if a and (not b or not c) or b and (not a or not c) or c and (not b or not a):
发布于 2013-05-13 20:32:16
这样如何:
conditions = [a, b, c]
if any(conditions) and not all(conditions):
...
其他变体:
if 1 <= sum(map(bool, conditions)) <= 2:
...
发布于 2013-05-13 20:55:57
关于:(唯一条件)
if (bool(a) + bool(b) + bool(c) == 1):
请注意,如果您也允许两个条件,则可以这样做
if (bool(a) + bool(b) + bool(c) in [1,2]):
发布于 2013-05-13 20:34:09
如果三个条件中只有一个为True
,则返回True
。这可能就是您在示例代码中想要的。
if sum(1 for x in (a,b,c) if x) == 1:
https://stackoverflow.com/questions/16522111
复制相似问题