如何一次比较多个事物

A-P*_*A-P 0 python operator-precedence

让我们说a ='hi'

我想知道a是否是以下任何'hi','yes'或'no'我可以运行

a='hi'
a=='hi' or a=='yes' or a=='no'
>>>True
Run Code Online (Sandbox Code Playgroud)

但是,让我们说这是一个很长的可能性列表,所以我只想说

a='hi'
a==('hi' or 'yes')
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到的答案是真的但是当我做这样的事情时:

a==('yes' or 'hi')
>>>False
Run Code Online (Sandbox Code Playgroud)

然后这也很奇怪

a==('yes' and 'hi')
>>>True
Run Code Online (Sandbox Code Playgroud)

但如果我再次切换它们

a==('hi' and 'yes')
>>>False
Run Code Online (Sandbox Code Playgroud)

有人可以解释这里发生的事情

kev*_*nji 7

你的一些行评估的原因,True而其他人评估的False原因仅仅是因为Python中的工作方式and/ or工作方式:

表达式x and y首先评估x; 如果x为false,则返回其值; 否则,将评估y并返回结果值.

表达式x or y首先评估x; 如果x为真,则返回其值; 否则,将评估y并返回结果值.

因此,让我们来看看你的案例.

('hi' or 'yes')
Run Code Online (Sandbox Code Playgroud)

'hi'是真实的,所以这个表达式评估为'hi'.a == 'hi'评估为True.

('yes' or 'hi')
Run Code Online (Sandbox Code Playgroud)

同样的推理,除了它现在评估'yes'.a == 'yes'False.

('yes' and 'hi')
Run Code Online (Sandbox Code Playgroud)

由于'yes'是真实的,表达式评估为'hi',并且a == 'hi'True.

('hi' and 'yes')
Run Code Online (Sandbox Code Playgroud)

最后,因为这个评估'yes',a == 'yes'False.

如果你想测试一个字符串是否是多个东西之一,测试它是否在一个集合中:

if a in {'hi', 'yes', 'no'}:
    # Do something
Run Code Online (Sandbox Code Playgroud)