我有一个关于 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)
在这里,我希望列表为空,因为没有项目满足条件 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)
我得到的output#2是
>>> ans
['schoolteacher', 'mathematics teacher'] # I expected a list of words containing sub1 or sub2 as their substrings
我看到了一个类似的解决方案 here ,但它并不能完全解决我的问题。在使用 and
和 or
时,我两次都得到了我不期望的结果。为什么在这两个操作期间都会发生这种情况?
最佳答案
“salesmanager”中的(“teacher”和“sales”)
在 Python 和英语中的含义不同。
在英语中,它是 ("salesmanager"中的"teacher") 和 ("salesmanager"中的"sales")
的同义词(Python 会按您认为的方式理解,并评估为错误
).
另一方面,Python 将首先评估 "teacher"和 "sales"
,因为它在括号中,因此具有更高的优先级。 and
如果为假则返回第一个参数,否则返回第二个参数。 "teacher"
不是假的,因此 "teacher"和 "sales"
的计算结果为 "sales"
。然后,Python 继续计算“salesmanager”中的 “sales”
,并返回 True
。
关于python - 为什么此 Python 语句中的 'and/or' 操作行为异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821841/