问题
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
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".
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.
Thanks!
回答1:
Use any
here:
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
Boolean or
:
x or y
is equal to : if x is false, then y, else x
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
As an non-empty string is True in python, so your conditions are equivalent to:
("workspace") in command and ("3" in command)
help on 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.
>>>
回答2:
"workspace" or "screen" or "desktop" or "switch"
is an expression, which always evaluate to "workspace"
.
Python's object has truth value. 0
, False
, []
and ''
are false, for example. the result of an or
expression is the first expression that evaluates to true. "workspace" is "true" in this sense: it is not the empty string.
you probably meant:
"workspace" in command or "screen" in command or "desktop" in command or "switch" in command
which is a verbose way to say what @Ashwini Chaudhary has used any
for.
来源:https://stackoverflow.com/questions/16888334/understanding-condition-logic