python - 冷凝比较

时间:2011-10-06 17:37:25

标签: python comparison comparison-operators

我是这里的新成员,也是python的新成员。我的问题如下,有这样一条线是否有效?

if x or y is 'whatever':

我在解释器中对此进行了测试,结果不一致。看起来这条线会产生更一致和预期的结果

if (x or y) is 'whatever':

或者最好明确地将所有内容都列为

if x is 'whatever' or y is 'whatever':

这最后一个总是有效,但我只是想让我的代码更简洁,同时仍然遵循最佳实践。我尝试进行搜索,以便不要问多余的问题,但是搜索“是”或“和”并且“相当困难”。提前感谢您的任何帮助。

编辑:感谢大家的快速回复。当我需要'或'

时,这对我来说非常适合
if 'whatever' in [x,y]:

但如果我需要一个'和',我该如何缩小呢?

if x == 'whatever' and y == 'whatever':

4 个答案:

答案 0 :(得分:8)

or与英语不同。

如果x是true-ish值,则

x or y返回x,否则返回y。如果字符串不是空的话,字符串就是真的。

更糟糕的是,“是”的优先级高于“或”,因此您的表达式与x or (y is 'whatever')相同。因此,如果x不为空,则返回x(这将为true,因此if将执行)。如果x为空,则会评估y is 'whatever'

BTW:不要使用“is”来比较值相等,使用==。

你想要这个(parens可选):

if (x == 'whatever') or (y == 'whatever'):

或更简洁,但更陌生:

if 'whatever' in [x, y]:

答案 1 :(得分:3)

Python不是英语。

if x or y is 'whatever':

表示:

if x or (y is 'whatever'):

哪个是X是真的或者y是'无论'

if (x or y) is 'whatever':

x or y变为x或y。如果x为真,那么它返回X,否则它变为Y.然后将结果与'whatever'进行比较。

永远不要将字符串与is进行比较。应使用==比较字符串。意味着有些不同的东西,有时候是偶然的。

您的实际请求可以写成:

if 'whatever' in [x,y]:

这将检查列表[x,y]中的字符串是否为任何内容。

答案 2 :(得分:1)

我认为这样可行:

if "whatever" in (x, y):

虽然有点奇怪。

答案 3 :(得分:1)

if x or y is 'whatever' # this is akin to if x or (y is 'whatever')

if (x or y) is 'whatever': # (x or y) returns the first non-false value...

if x is 'whatever' or y is 'whatever': # this is valid and correct (aside from the fact you shouldn't be using `is`, see below)

你可能有

if 'whatever' in (x, y)

或者,如果条件列表较长,最好使用“any”功能:

if any([condition(k) for k in list])

但是在你曝光的情况下这是过度的,因为你只想知道[x,y]中是否包含'what'。

更新:

认为'is'实际上是在比较内存地址,并且(如指出here)在字符串上使用它是不好的做法。