Python 清单3中的or语句
我正在为我的Python3类制作一个tic-tac-toe程序,我想知道为什么我的计算机win-move不能正常工作。“list”函数中的“or”似乎没有正确计算。是否有其他方法来完成评估条件Python 清单3中的or语句,python,python-3.x,list-comprehension,python-3.4,Python,Python 3.x,List Comprehension,Python 3.4,我正在为我的Python3类制作一个tic-tac-toe程序,我想知道为什么我的计算机win-move不能正常工作。“list”函数中的“or”似乎没有正确计算。是否有其他方法来完成评估条件 def winningMoves(): print('starting computer winning move') i = [1, 2, 3, 7] if (1 and 2 in i) or (5 and 7 in i) or (6 and 9 in i): d
def winningMoves():
print('starting computer winning move')
i = [1, 2, 3, 7]
if (1 and 2 in i) or (5 and 7 in i) or (6 and 9 in i):
drawBoardlist[3] = computerCharacter
elif (2 and 3 in i) or (4 and 7 in i) or (5 and 9 in i):
drawBoardlist[1] = computerCharacter
elif (1 and 2 in i) or (3 and 5 in i) or (8 and 9 in i):
drawBoardlist[7] = computerCharacter
elif (7 and 8 in i) or (1 and 5 in i) or (3 and 6 in i):
drawBoardlist[10] = computerCharacter
else:
print('No winning moves')
return
(i中的1和2)
被解析为((i)中的(1)和(2))
。相反,你的意思可能是
((1 in i) and (2 in i))
同样,对于所有其他条件
比如说,
In [47]: i = [1, 2, 3, 7]
In [48]: (100 and 2 in i)
Out[48]: True
In [49]: ((100 in i) and (2 in i))
Out[49]: False
显示的
和
的优先级低于中的。因此
中的比和绑定得更紧密,因此
中的在之前绑定到(2 in i)
,并且
绑定1
和(2 in i)
以形成1和(2 in i)
这就是为什么(i中的1和2)
被解析为((i)中的(1)和(2))
顺便说一下,检查一个项目是否在列表中是一个O(n)操作。如果您经常这样做,那么您最好先将列表放入一个集合中,因为检查集合中的成员资格是O(1)
或
iset = set(i)
if (1 in iset and 2 in iset)
if iset.issuperset((1, 2))