TypeError:|:'tuple'和'bool'不支持的操作数类型

时间:2015-02-27 07:21:45

标签: python boolean

当我尝试使用“|”时出现了奇怪的错误运算符in if with tuple。

#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'

1 个答案:

答案 0 :(得分:3)

你需要根据需要使用parens,就像这样

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,这基本上是一个布尔值。所以,你有效地做了

tuple | boolean

这就是你收到这个错误的原因。

注意: |在Python中称为按位OR。如果你的意思是逻辑OR,你需要像这样写

if(((courd[0] - 1, courd[1] - 1) in d) or (2 == 2)):
    pass

现在,首先评估(courd[0] - 1, courd[1] - 1)以创建元组,然后检查元组是否存在于d中(这将返回TrueFalse ,布尔值)然后(2 == 2)将被评估,返回True。现在,逻辑or很乐意使用两个布尔值。