Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 清单3中的or语句_Python_Python 3.x_List Comprehension_Python 3.4 - Fatal编程技术网

Python 清单3中的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

我正在为我的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):
        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))