【问题标题】:Why are 'and/or' operations in this Python statement behaving unexpectedly?为什么此 Python 语句中的“和/或”操作出现意外行为?
【发布时间】:2019-02-22 07:11:16
【问题描述】:

我有一个关于 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)

我得到的输出#2

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

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

【问题讨论】:

  • (sub1 and sub2) in item 括号中的表达式的结果是什么?这将根据item 进行检查。
  • (sub1 and sub2) in item更改为sub1 in item and sub2 in item

标签: python logical-operators


【解决方案1】:

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

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

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

【讨论】:

  • 据我所知,所有语言都优先考虑括号,而不仅仅是 Python。但是您在解释 Python 为 ( X and Y ) 返回什么是正确的
  • 您可能希望为此模式推荐 anyall
  • @NeilG 我想了想,然后发现需要解释优先级的级别与某人可以理解生成器和函数的级别(例如all)之间存在很大差异,并且它会只是混淆提问者(即准备从中受益的人不会首先寻找这个问题)。
【解决方案2】:

andor 运算符不会像您认为的那样做。试着分解你的表达方式:

if sub1 in item or sub2 in item:

if sub1 in item and sub2 in item:

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

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

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

(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

【讨论】:

    最近更新 更多