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

标签 python logical-operators

我有一个关于 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 ,但它并不能完全解决我的问题。在使用 andor 时,我两次都得到了我不期望的结果。为什么在这两个操作期间都会发生这种情况?

最佳答案

“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/

相关文章:

JavaScript 逻辑或无效赋值

ios - Playground 执行失败 : <EXPR>:15:33: error: type 'Int' does not conform to protocol 'BooleanType'

C 关系运算符输出

ios - 在 reduce 中使用逻辑运算符作为组合闭包

python - 从 pandas.core.series.Series 中提取数据时出现 KeyError

ruby - 需要澄清 Ruby 逻辑运算符

python - 如何使用 python 使用 Canvas Data REST API?

python - 如何从 numpy 数组转换为文件字节对象?

c++ - 有人知道将图像分成任意形状的 C++ 或 Python 库吗?

python - 区分类型别名和实际类的约定?