if command in python

前端 未结 3 1661
灰色年华
灰色年华 2021-01-20 18:03
if \"aa\" or \"bb\" or \"cc\" or \"dd\" or \"ee\" or \"ff\" in attrs[\"show\"]:
    self.xx = xxxx

I have a code like this, to check if attrs[\"sho

相关标签:
3条回答
  • 2021-01-20 18:32

    Your IF statement is not testing for anything. It WILL always evaluate as true, because of the way it is written.

    You are asking python:

    Is aa true
    Is bb true
    ...
    

    Python says 'Yes, "aa" is true, because its there!'

    Correct your if statement or find a better way to find the values in the list:

    any(x in ['aa','bb','cc','dd','ee','ff'] for x in attrs["show"])
    
    0 讨论(0)
  • 2021-01-20 18:48

    In Python, and or evaluates to its first True operand (since True or'd with anything is True, Python doesn't need to look further than the first operand).

    So:

    "aa" or "bb" or "cc" or "dd" or "ee" or "ff" in attrs["show"]
    

    ... evaluates to:

    "aa"
    

    Which is True, because it's a non-empty string. The rest of the line is not even considered because it does not need to be.

    So your if statement always executes because it is always True.

    What you want is something like:

    "aa" in attrs["show"] or "bb" in attrs["show"] or "cc" in attrs["show"] ...
    

    This gets very wordy, so you can use any along with a generator expression to write it more succinctly.

    any(s in attrs["show"] for s in ["aa", "bb", "cc", "dd", "ee", "ff"])
    
    0 讨论(0)
  • Try the following:

    if any(s in attrs["show"] for s in ("aa", "bb", "cc", "dd", "ee", "ff")):
        self.xx = xxxx
    

    Your current if statement will always evaluate to True, because instead of checking if each string is in attrs["show"] you are checking if "aa" is True, or if "bb" is True, and on and on. Since "aa" will always evaluate as True in a Boolean context, you will always enter the if clause.

    Instead, use the any() function as in my example, which accepts an iterable and returns True if any of its elements are True. Similar to a bunch of or's as in your code, this will short-circuit as soon as it finds an element that is True. In this example, the above code is equivalent to the following (but much more concise!):

    if ("aa" in attrs["show"] or "bb" in attrs["show"] or "cc" in attrs["show"] or
        "dd" in attrs["show"] or "ee" in attrs["show"] or "ff" in attrs["show"]):
        self.xx = xxxx
    
    0 讨论(0)
提交回复
热议问题