Python 测试多个字符串';在';列表理解中的条件

Python 测试多个字符串';在';列表理解中的条件,python,list-comprehension,multiple-conditions,Python,List Comprehension,Multiple Conditions,我试图使用列表理解向python if语句添加多个'or'子句。我的代码如下所示。我想保留这份清单。就伪代码而言,逻辑将是: Alive_Beatles=包含“(披头士)”和('Paul'、'Yoko'或'Ringo')的每个名字 代码只返回Paul并跳过Ringo和Yoko Names = ["John Lennon (Beatle)", "Paul McCartney (Beatle)", "Ringo Starr (Beatle)", "Yoko Ono (Beatle)", "Mick

我试图使用列表理解向python if语句添加多个'or'子句。我的代码如下所示。我想保留这份清单。就伪代码而言,逻辑将是:

Alive_Beatles=包含“(披头士)”和('Paul'、'Yoko'或'Ringo')的每个名字

代码只返回Paul并跳过Ringo和Yoko

Names = ["John Lennon (Beatle)",  "Paul McCartney (Beatle)", "Ringo Starr (Beatle)", "Yoko Ono (Beatle)", "Mick Jagger (Rolling Stone)", "Brian Jones (Rolling Stone)", "Alex Jones (na)", "Adam Smith (na)"]
Alive_Beatles = [n for n in Names if ("Beatle" and ("Paul" or "Ringo" or "Yoko")) in n]

print Alive_Beatles

如果每个名称在n中
,则需要显式测试:

[n for n in Names if ("Beatle" in n and ("Paul" in n or "Ringo" in n or "Yoko" in n))]
否则,
将使用搜索字符串的真值(每个非空字符串始终为真),并最终测试n中的
Paul(或
的第一个真值)

报告明确提到这一点:

4.2. 布尔运算-and、or、not 以下是布尔运算,按优先级升序排列:

Operation     Result                                Notes
x or y        if x is false, then y, else x         (1)
x and y       if x is false, then x, else y         (2)
not x         if x is false, then True, else False  (3)
笔记: (1) 这是一个短路运算符,因此只有当第一个参数为false时,它才会计算第二个参数

(2) 这是一个短路运算符,因此它仅在第一个参数为真时计算第二个参数

(3) not的优先级低于非布尔运算符,因此not a==b被解释为not(a==b),而a==not b是一个语法错误


因此,
“披头士”和(…)
根据(2)第二个参数求值,因为
“披头士”
是真实的,根据(1)它求值到链接的
的第一个参数:
“保罗”
,因为它也是真实的。

这并没有达到您期望的效果,因为表达式

("Paul" or "Ringo" or "Yoko")
计算结果为“Paul”
。在解释器提示下键入以确认这一点

即使是这样,也只是因为

("Beatle" and ("Paul" or "Ringo" or "Yoko")) 

也可计算为“Paul”

最简单的解决方案是只列出

[n for n in Names if "Beatle" in n and ("Paul" in n or "Ringo" in n or "Yoko" in n)]
但你可以利用它来更接近你最初的尝试:

[n for n in Names if "Beatle" in n and any(x in n for x in ("Paul", "Ringo", "Yoko"))]

由于第二个问题而关闭,重新打开,但愿我没有重新打开。需要咖啡。@timgeb干杯,去拿你的咖啡。这个问题的标题很容易让人误解,特别是考虑到它是为了一些与列表理解无关的东西而关闭的。怎么办?我修改了标题以反映实际问题。我想我们可以把它关闭,虽然我不认为这是一个完全的骗局,这里的答案更好。