if command in python

前端 未结 3 1691
灰色年华
灰色年华 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:52

    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
    

提交回复
热议问题