python多个比较运算符语句解析

2015-10-30  本文已影响390人  偷天神猫

在python神奇的世界里

你可能见过这个样的语句:

if (5 == len(set(vec[i]+i for i in cols))== len(set(vec[i]-i for i in cols))):   
    print vec

或是这样的语句​:

​a=[1,2,3,4,5]
b=[1,2,3,4,5]

if(5 == len(a) == len(b)):   
    print "yes"
else:   
    print "no"

​你可能会疑惑“==”比较符连在一起是什么意思?

按照c的语法规则,显然我们要先从左边第一个“==”开始,

以上题为例,若“5 == len(a)”​则返回布尔值“True”,然后再比较“True”和“len(b)”是否相等。但是根据python例程的使用情况,我们推测出,python中的“5== len(a)== len(b)”显然不是这样比较的。

我们在​IDLE中输入“help('==')”,得到以下信息,我只摘录出主要部分,其他的信息读者有兴趣的话可以自己输入命令查看。

Unlike C, all comparison operations in Python have the same priority,which is lower than that of any arithmetic, shifting or bitwiseoperation.……

Comparisons can be chained arbitrarily, e.g.,
"x < y <= z" isequivalent to "x < y and y <= z",​……

按照该官方文档解释,

”5== len(a)== len(b)“等价于”5== len(a) and len(a)== len(b)“

这样是不是就一目了然了呢?​

上一篇 下一篇

猜你喜欢

热点阅读