问题描述
我有这部分代码:
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:
作为数字运算符,&
运算符具有优先级高于比较运算符,而布尔运算符的优先级较低.表达式 opg == 160&因此opc == 129
被解释为 opg ==(160& 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和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!