当我试图在if中对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'

最佳答案

你需要根据需要使用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,则需要这样编写
if(((courd[0] - 1, courd[1] - 1) in d) or (2 == 2)):
    pass

现在,将首先评估(courd[0] - 1, courd[1] - 1)以创建元组,然后如果在d中存在元组,则将检查元组(这将返回TrueFalse,布尔),然后将计算返回(2 == 2)True。现在logicalor很乐意与两个布尔人一起工作。

关于python - TypeError:|:'tuple'和'bool'不支持的操作数类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28759606/

10-10 19:24