为什么要“(在arr中为'a')在arr中"? !=“在arr中的arr中的'a'"? [英] Why "('a' in arr) in arr" != "'a' in arr in arr"?

查看:265
本文介绍了为什么要“(在arr中为'a')在arr中"? !=“在arr中的arr中的'a'"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是('a' in arr) in arr!= 'a' in arr in arr?

arr = [1, True, 'a', 2]
print(('a' in arr) in arr)  # -> True
print('a' in arr in arr)  # -> False

推荐答案

第6.10节Python语言参考中的内容讨论了比较运算符和比较链. in被视为比较运算符,因此其行为与<相同,依此类推.对于显式分组,没有括号的情况下,对于任何两个比较运算符,x OP1 y OP2 z等效于x OP1 y and y OP2 z.

Section 6.10 of the Python language reference discusses comparison operators and comparison chaining. in is considered a comparison operator, and so behaves the same as <, etc. Without parentheses for explicit grouping, x OP1 y OP2 zis equivalent to x OP1 y and y OP2 z for any two comparison operators.

这意味着

'a' in arr in arr

不带括号,等同于

'a' in arr and arr in arr

arr本身不是元素,因此表达式为False.

arr is not an element of itself, so the expression is False.

括号禁用了链接,所以

('a' in arr) in arr

与其他嵌套表达式一样,对

进行求值.首先将'a' in arr评估为True值,然后对True in arr进行评估以产生True.

is evaluated like any other nested expression. 'a' in arr is evaluated first to the value True, then True in arr is evaluated to also produce True.

这篇关于为什么要“(在arr中为'a')在arr中"? !=“在arr中的arr中的'a'"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆