Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65893563/simplify-series-of-elif-statements-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...