【发布时间】: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,但它并不能完全解决我的问题。这两次我都得到了使用and 和or 时没有预料到的结果。为什么在这两个操作中都会发生这种情况?
【问题讨论】:
-
(sub1 and sub2) in item括号中的表达式的结果是什么?这将根据item进行检查。 -
将
(sub1 and sub2) in item更改为sub1 in item and sub2 in item