sha*_*ait 2 python bitwise-operators logical-and
大家好我有这部分代码:
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))
Run Code Online (Sandbox Code Playgroud)
我有一系列的类型
1362581670 2459546910990453036 156 0 30 0
Run Code Online (Sandbox Code Playgroud)
我想只取第三个和第四个元素分别为160和129的行.这段代码不起作用.我需要做一些演员吗?我认为opg == 160正在使用int来进行campare int ...
你对运营商感到困惑; and是正确的布尔测试,&是一个二进制位运算符:
if opg == 160 and opc == 129:
Run Code Online (Sandbox Code Playgroud)
作为数字运算符,&运算符的优先级高于比较运算符,而布尔运算符的优先级较低.因此,表达式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))
Run Code Online (Sandbox Code Playgroud)