了解条件逻辑

2024-04-23 21:59:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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

奇怪的是,如果命令是“desktop three”,但如果命令是“switch three”,那么这个正确的计算并执行xdotool行,“workspace 3”也可以工作,但“workspace 3”不起作用。在

所以,我的问题是,这里发生了什么?这里的条件流是什么,它是如何评估的?我怎样才能最好地解决它?我有一些想法(比如“工作区”可能被简单地评估为True,因为它与“in command”没有绑定,并且被评估为布尔值),但是我想对它有一个真正的理解。在

谢谢!在


Tags: orin命令程序true解析器方式workspace
2条回答

在此处使用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,则选择最后一个。在

^{pr2}$

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

^{3}$

关于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.
>>> 

"workspace" or "screen" or "desktop" or "switch"是一个表达式,其计算结果始终为"workspace"。在

Python的对象具有真值。^例如,{}、False[]和{}都是false。or表达式的结果是第一个计算结果为true的表达式。“从这个意义上说,workspace“是“真的”:它不是空字符串。在

你可能是说:

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

这是一个冗长的方式来说明@Ashwini Chaudhary使用any来做什么。在

相关问题 更多 >