替换If/Else语句Python



我想让一个井字游戏用户输入X和O的所有列和行的一行字符串,比如'O_OOXOOX',我把它们变成嵌套列表,比如[['O','_','O'],[[O',X','O'],[O','X','X']]

我的问题是如何替换下面所有的if-elif?因为它看起来很多。

for i in range(3):
if nested_list[i][0] == nested_list[i][1] == nested_list[i][2] == 'O':
print('O wins')
elif nested_list[0][i] == nested_list[1][i] == nested_list[2][i] == 'O':
print('O wins')
elif nested_list[0][0] == nested_list[1][1] == nested_list[2][2] == 'O':
print('O wins')
elif nested_list[0][2] == nested_list[1][1] == nested_list[2][0] == 'O':
print('O wins')
elif nested_list[i][0] == nested_list[i][1] == nested_list[i][2] == 'X':
print('X wins')
elif nested_list[0][i] == nested_list[1][i] == nested_list[2][i] == 'X':
print('X wins')
elif nested_list[0][0] == nested_list[1][1] == nested_list[2][2] == 'X':
print('X wins')
elif nested_list[0][2] == nested_list[1][1] == nested_list[2][0] == 'X':
print('X wins')

可能有更好的解决方案,但可能是这样的?

for i in range(3):
a = set(nested_list[i,:])
b = set(nested_list[:,i])
if(len(a) == 1 && nested_list[i,0] != '_')
print(nested_list[i,0], " wins")
elif(len(b) == 1 && nested_list[0,i] != '_')
print(nested_list[0,i], " wins")
if (((nested_list[0][0] == nested_list[1][1] == nested_list[2][2]) || nested_list[2][0] == nested_list[1][1] == nested_list[0][2])) && nested_list[1][1] != '_'):
print(nested_list[1][1], " wins")

我找到了另一个解决方案:

arr = ['X', 'X', 'O', 'O', 'O', 'X', 'X', 'O', 'X']

我确定了一个可能获胜的嵌套列表

matches = [[0, 1, 2], [3, 4, 5],
[6, 7, 8], [0, 3, 6],
[1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]]
for i in range(8):
if(arr[matches[i][0]] == 'X' and
arr[matches[i][1]] == 'X' and
arr[matches[i][2]] == 'X'):
print(X wins)
else:
print(O wins)

现在我正试图找出其他的可能性例如如果游戏没有结束如果连续有3个X和O,那么游戏是不可能的。。。

最新更新