[英]Simplify series of elif statements in Python
I'm creating a tic-tac-toe ai program with a board formatted like this:我正在创建一个井字游戏 ai 程序,其板的格式如下:
board = [['X','O','X'],[' ','O',' '],[' ',' ',' ']]
I have a series of elif
statements like this, which checks if a side is empty, and if so return the board position of that side:我有一系列这样的elif
语句,它检查一侧是否为空,如果是则返回该侧的板 position:
if board[1][0] == ' ':
return 1, 0
elif board[1][2] == ' ':
return 1, 2
elif board[0][1] == ' ':
return 0, 1
else:
return 2, 1
Since the condition is the same, is there a faster way of doing this?既然条件相同,有没有更快的方法呢?
Update 1: After implementing kaya3's answer the program runs 0.05 - 0.2 seconds faster更新 1:实施 kaya3 的答案后,程序运行速度快 0.05 - 0.2 秒
If you want to do the same thing for a series of different values, put them in a list, and then loop over it:如果你想对一系列不同的值做同样的事情,把它们放在一个列表中,然后循环它:
sides = [(1, 0), (1, 2), (0, 1), (2, 1)]
for x, y in sides:
if board[x][y] == ' ':
return x, y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.