为什么此 Python 语句中的 'and/or' 操作行为异常?

Why are 'and/or' operations in this Python statement behaving unexpectedly?

我有一个关于 Python 的概念性问题。这是代码

list1=['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
sub1 = "teacher"
sub2 = "sales"
ans=[]

for item in list1:
    if (sub1 and sub2) in item:
        ans.append(item)

在这里,我希望列表为空,因为 none 项满足条件 if sub1 and sub2 in item: 但是当我打印列表时,我得到 output#1 像这样

>>> ans
['salesperson', 'sales manager'] # I expected an empty list here

此外,当我使用 or 而不是 and 时,如下所示

for item in list1:
    if (sub1 or sub2) in item:
        ans.append(item)

我得到的输出#2

>>> ans
['schoolteacher', 'mathematics teacher'] # I expected a list of words containing sub1 or sub2 as their substrings

我看到了一个类似的解决方案 ,但它并没有完全解决我的问题。在使用 andor 时,我两次都得到了我不期望的结果。为什么在这两个操作期间都会发生这种情况?

andor 运算符并不像您认为的那样。尝试分解你的表情:

if sub1 in item or sub2 in item:

if sub1 in item and sub2 in item:

and 运算符计算其左侧操作数,如果结果为真,returns 右侧操作数,否则为左侧操作数。

or 运算符计算其左侧操作数,如果结果为假,returns 右侧操作数,否则为左侧操作数。

因此,您的第一个表达式的计算结果如下:

(sub1 and sub2) in item
("teacher" and "sales") in item
("sales") in item

这不是你所期望的。

与您的第二个表达式类似:

(sub1 or sub2) in item
("teacher" or "sales") in item
("teacher") in item

("teacher" and "sales") in "salesmanager"在Python和英语中的意思不一样。

在英语中,它是 ("teacher" in "salesmanager") and ("sales" in "salesmanager") 的同义词(Python 会按照您的想法理解,并评估为 False)。

另一方面,

Python 将首先评估 "teacher" and "sales",因为它在括号中,因此具有更高的优先级。如果为假,and 将 return 第一个参数,否则为第二个参数。 "teacher" 不是假的,所以 "teacher" and "sales" 计算为 "sales"。然后,Python继续计算"sales" in "salesmanager",returns True.