当我尝试使用“|”时出现奇怪的错误带有元组的 if 中的运算符。
#example
Myset = ((1, 3), (4, 6), (3, 1), (2, 2), (3, 5), (2, 4), (3, 3))
courd = (4,6)
if(courd[0] - 1 ,courd[1] - 1 in d ):
isSafe = True # work as expected
但如果我尝试这样的事情:
if((courd[0] - 1 ,courd[1] - 1 in d) | 2==2 ): # or something else that involved "|"
isSafe = True
我得到了
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
if((courd[0] - 1 ,courd[1] - 1 in d )| (2 == 2)):
TypeError: unsupported operand type(s) for |: 'tuple' and 'bool'
最佳答案
你需要使用括号,根据需要,像这样
if((courd[0] - 1, courd[1] - 1) in d):
pass
现在,它将创建一个元组 (courd[0] - 1, courd[1] - 1)
并检查它是否在 d
中。在下一个案例中,
if((courd[0] - 1, courd[1] - 1 in d) | 2 == 2):
pass
(courd[0] - 1, courd[1] - 1 in d)
将首先被评估,这将创建一个元组。然后 2 == 2
将被评估(因为 |
的优先级低于 ==
)为 True
,这基本上是一个 boolean 值。所以,你正在有效地做
tuple | boolean
这就是您收到该错误的原因。
注意 |
在Python中被称为按位或。如果你的意思是逻辑OR
,你需要这样写
if(((courd[0] - 1, courd[1] - 1) in d) or (2 == 2)):
pass
现在,(courd[0] - 1, courd[1] - 1)
将首先被评估以创建一个元组,然后将检查该元组是否存在于 d
(这将返回 True
或 False
,一个 boolean 值),然后 (2 == 2)
将被评估返回真
。现在逻辑 or
会很高兴地使用两个 boolean 值。
关于python - 类型错误 : unsupported operand type(s) for |: 'tuple' and 'bool' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28759606/