How to check if one of the following items is in a list?

前端 未结 14 2190
终归单人心
终归单人心 2020-11-22 17:02

I\'m trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the

14条回答
  •  余生分开走
    2020-11-22 17:54

    Think about what the code actually says!

    >>> (1 or 2)
    1
    >>> (2 or 1)
    2
    

    That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:

    def or(x, y):
        if x: return x
        if y: return y
        return False
    

    In the first example, x == 1 and y == 2. In the second example, it's vice versa. That's why it returns different values depending on the order of them.

提交回复
热议问题