且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python bitand(&)vs和

更新时间:2022-05-19 17:02:40

您对运算符感到困惑; and 是正确的布尔测试& 二进制按位运算符代替:

You got confused with the operators; and is the correct boolean test, & is a binary bitwise operator instead:

if opg == 160 and opc == 129:

作为数字运算符,& 运算符具有

As a numeric operator, the & operator has a higher precedence than comparison operators, while the boolean operators have a lower precedence. The expression opg == 160 & opc == 129 is thus interpreted as opg == (160 & opc) == 129 instead, which is probably not what you wanted.

您可以稍微简化代码:

for line in response.body.splitlines():
    if line:
        line = map(int, line.split())
        opg, opc, value = line[2], line[3], line[5]
        if opg == 160 and opc == 129:
            ret['success'] = "valore: %s" % (value)
            self.write(tornado.escape.json_encode(ret))