本文介绍了测试列表理解中的多个字符串“处于"条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用列表理解将多个或"子句添加到python if语句中.我的代码如下所示.我想保持清单的理解力.就伪代码而言,逻辑将简单地为:

I am trying to add multiple 'or' clauses to a python if statement using list comprehension. My code is shown below. I would like to keep the list comprehension. In terms of pseudocode, the logic would simply be:

Alive_Beatles =每个包含'(Beatle)'("Paul","Yoko"或"Ringo")的名称

Alive_Beatles = each name that contains '(Beatle)' and either ('Paul', 'Yoko' or 'Ringo')

该代码仅返回Paul并跳过Ringo和Yoko.

The code only returns Paul and skips Ringo and 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

推荐答案

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

You need to test each name explicitly if it's in n:

[n for n in Names if ("Beatle" in n and ("Paul" in n or "Ringo" in n or "Yoko" in n))]

否则,andor使用搜索字符串的真值(每个非空字符串始终为True),最后测试是否Paul in n(or的第一个真值)

Otherwise the and and or use the truth value of you search strings (and each non-empty string is always True) and finally tests if Paul in n (the first truth value of the ors).

文档明确提到了这一点:

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时才对第二个参数求值.

Notes:

(1) This is a short-circuit operator, so it only evaluates the second argument if the first one is false.

(2)这是一个短路运算符,因此只有第一个为true时,它才求值第二个参数.

(2) This is a short-circuit operator, so it only evaluates the second argument if the first one is true.

(3)的优先级没有比非布尔运算符低,因此a == b不会被解释为not(a == b),而a == not b是语法错误.

(3) not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

所以"Beatle" and (...)根据(2)对第二个参数求值,因为"Beatle"是真实的,而根据(1)它对链接的or s的第一个参数求值:"Paul"因为它也是真实的

So "Beatle" and (...) evaluates according to (2) to the second argument because "Beatle" is truthy and according to (1) it evaluates to the first argument of the chained ors: "Paul" because it's also truthy.

这篇关于测试列表理解中的多个字符串“处于"条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:43