理解条件逻辑

时间:2013-06-02 23:41:42

标签: python conditional-statements boolean-logic

我正在编写一个python程序,它在计划英语中使用给定的句子并从中提取一些命令。它现在非常简单,但我的命令解析器得到了一些意想不到的结果。在仔细研究之后,似乎我的条件逻辑没有像我预期的那样进行评估。

这当然是一种非常不优雅的方式,而且过于冗长。我将完全重组它,可能使用神经网络或正则表达式或它们的组合。但我确实想要在我前进之前理解这个错误背后的逻辑,因为这是一个非常重要的事情要知道。这是代码的一部分:

if  (("workspace" or "screen" or "desktop" or "switch")  in command) and 
     (("3" or "three" or "third") in command):
    os.system("xdotool key ctrl+alt+3")
    result = True

奇怪的是,如果命令是“桌面三”,这个正确的评估和制定xdotool行,但如果命令是“switch three”,那么也不是“工作区3”,但不是“工作空间3”。

所以,我的问题是,这里发生了什么?这里的条件流是什么,它是如何评估的?我怎么能最好地解决它?我有一些想法(比如可能的“工作空间”总是被简化为True,因为它没有与“in command”绑定并被评估为布尔值),但我希望对它有一个非常可靠的理解。

谢谢!

2 个答案:

答案 0 :(得分:3)

在此处使用any

screens = ("workspace" , "screen" , "desktop" , "switch")
threes = ("3" , "three", "third")

if any(x in command for x in screens) and any(x in command for x in threes):
    os.system("xdotool key ctrl+alt+3")
    result = True

布尔or

x or y等于:if x is false, then y, else x

简单来说:在一系列or条件中,选择了第一个True值,如果所有值均为False,则选择最后一个值。

>>> False or []                     #all falsy values
[]
>>> False or [] or {}               #all falsy values
{}
>>> False or [] or {} or 1          # all falsy values except 1
1
>>> "" or 0 or [] or "foo" or "bar" # "foo" and "bar"  are True values
'foo

由于python中的非空字符串为True,因此您的条件等同于:

("workspace") in command and ("3" in command)

any上的帮助:

>>> print any.__doc__
any(iterable) -> bool

Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
>>> 

答案 1 :(得分:2)

"workspace" or "screen" or "desktop" or "switch"是一个表达式,总是评估为"workspace"

Python的对象具有真值。例如,0False[]''都是错误的。 or表达式的结果是第一个计算结果为true的表达式。在这个意义上,“workspace”是“真实的”:它不是空字符串。

你可能意味着:

"workspace" in command or "screen" in command or "desktop" in command or "switch" in command

这是一个详细说明@Ashwini Chaudhary使用any的内容的方式。

相关问题