我正在编写一个python程序,该程序以计划英语接受给定的句子,并从中提取一些命令.现在非常简单,但是我从命令解析器中得到了一些意想不到的结果.经过一番研究之后,看来我的条件逻辑并未按照我的预期进行评估.
I'm writing a python program that takes a given sentence in plan English and extracts some commands from it. It's very simple right now, but I was getting some unexpected results from my command parser. After looking into it a bit, it seems my condition-logic wasn't evaluating as I intended it to.
这当然是一种非常微不足道的方法,而且过于冗长.我将使用可能的神经网络或正则表达式或它们的组合来完全重组它.但是,在前进之前,我确实想了解该错误背后的逻辑,因为这是非常重要的事情.这是代码的一部分:
This is a really inelegant way to do it of course, and way too verbose. I'm going to be entirely restructuring it, using possibly neural networks or regular expressions or a combination of them. But I do want to understand the logic behind this error before I move forward, as it's a very import thing to know. Here's a section of the code:
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行,但如果命令为开关三",则不执行xdotool行,工作空间3"也有效,但工作空间三"无效.
The weird thing is that this correct evaluates and enacts the xdotool line if command is "desktop three" but does NOT if command is "switch three" also "workspace 3" works but not "workspace three".
所以,我的问题是,这是怎么回事?这里的条件流是什么,如何评估?我怎样才能最好地解决它?我有一些想法(例如可能将工作区"始终简单地评估为True,因为它不与"in command"绑定并且被评估为布尔值),但是我想对此有一个真正的了解.
So, my question is, what's happening here? What is the condition flow here, and how is it evaluating? How could I best fix it? I have some ideas (like possibly "workspace" being evaulated simply always to True because it's not binding with "in command" and is being evaluated as a boolean), but I want to get a really solid understanding of it.
谢谢!
推荐答案在此处使用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,则选择最后一个.
In simple words: in a chain of or conditions the first True value is selected, if all were False then the last one is selected.
>>> 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,因此您的条件等效于:
As an non-empty string is True in python, so your conditions are equivalent to:
("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. >>>更多推荐
了解条件逻辑
发布评论