简体   繁体   中英

Simplify series of elif statements in Python

I'm creating a tic-tac-toe ai program with a board formatted like this:

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM