Python bitand(&)vs和 [英] Python bitand (&) vs and

查看:69
本文介绍了Python bitand(&)vs和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这部分代码:

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

我有一系列if类型的线

I have a series if line of type

1362581670        2459546910990453036    156     0     30      0

我只想选择第三个元素和第四个元素分别为160和129的那一行.此代码无效.我需要铸造吗?我认为opg == 160正在努力将int与int结合使用.

I want to take only the line where the third and fourth element are respectively 160 and 129. This code doesn't work. Do I have to do some casting? I think opg==160 is working to campare int with int...

推荐答案

您对运算符感到困惑; 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))

这篇关于Python bitand(&)vs和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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