为什么 python 忽略条件的第一部分?

Why does python ignore the first part of a condition?

假设我有以下代码:

target = 'abc1234y'
if ('x' and 'y') in target:
    print('x and y are in target')

为什么 if ('x' and 'y') in target 是真的?

为什么这段代码不会产生错误?

为什么牙套没有效果?

这似乎不合逻辑,因为如果 ('x' and 'y') = true 那么 ('y' and 'x') 也应该为真,然而,事实并非如此。

同时表达式if ('y' and 'x') in targetfalse

您似乎混淆了 AND 运算符的工作原理。

'x' and 'y'
Out[1]: 'y'

'y' and 'x'
Out[1]: 'x'

所以在你的第一种情况下,你要检查 y 是否存在。相反,您检查字符串中是否存在 x

这里有两点需要考虑:

and 如何处理字符串

'x' and 'y' 不是 True.

'x' and 'y''y',这可能看起来令人困惑,但在查看 andor 的一般工作方式时它是有道理的:

  • a and b returns b 如果 a 是 True,否则 returns a.
  • a or b returns a 如果 a 是 True,否则 returns b.

因此:

  • 'x' and 'y''y'
  • 'x' or 'y''x'

括号的作用

括号在您的 if 语句中确实有影响。 in 的优先级高于 and 意味着如果你写

if 'x' and 'y' in target:

它的隐含含义与

相同
if 'x' and ('y' in target):

这只会检查 y 是否在目标字符串中。所以,使用

if ('x' and 'y') in target:

会有效果。您可以在 the Python docs about Expressions.

中看到整个 table 运算符优先级

解决方案

为了实现你想做的事情,@Prem 和@Olga 已经给出了两个很好的解决方案:

if 'y' in target and 'x' in target:

if all(c in target for c in ['x','y']):

因为它只检查目标中的 'y'。 你需要这样的东西:

target = 'abc1234y'
if 'y' in target and 'x' in target:
    print('x and y are in target')

您可能想改用 all if all(c in target for c in ['x','y']):...