大家好,我有这部分代码:
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))
我有一系列的线型
1362581670 2459546910990453036 156 0 30 0
我只想取第三个和第四个元素分别为 160 和 129 的行。 此代码不起作用。我需要做一些类型转换吗?我认为 opg==160 正在努力比较 int 和 int...
最佳答案
您对运算符感到困惑; and
is the correct boolean test , &
是 binary bitwise operator相反:
if opg == 160 and opc == 129:
作为数字运算符,&
运算符有一个 higher precedence than comparison operators ,而 bool 运算符的优先级较低。因此,表达式 opg == 160 & opc == 129
被解释为 opg == (160 & opc) == 129
,这可能不是您想要的。
您可以稍微简化您的代码:
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 (&) 与,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15251121/