Understanding condition logic

后端 未结 2 589
一个人的身影
一个人的身影 2021-01-25 05:17

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 resu

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 05:22

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

提交回复
热议问题