我有一个
list = [value, value, value, value, value, value, value, value, value]
其中值取值:-1,0或1。
if list[0] + list[1] + list[2] == 3:
alternative1 = True
elif list[0] + list[1] + list[2] == -3:
alternative2 = True
elif list[3] + list[4] + list[5] == 3:
alternative1 = True
elif list[3] + list[4] + list[5] == -3:
alternative2 = True
elif list[6] + list[7] + list[8] == 3:
alternative1 = True
elif list[6] + list[7] + list[8] == -3:
alternative2 = True
elif list[0] + list[3] + list[6] == 3:
alternative1 = True
elif list[0] + list[3] + list[6] == -3:
alternative2 = True
elif list[1] + list[4] + list[7] == 3:
alternative1 = True
elif list[1] + list[4] + list[7] == -3:
alternative2 = True
elif list[2] + list[5] + list[8] == 3:
alternative1 = True
elif list[2] + list[5] + list[8] == -3:
alternative2 = True
elif list[0] + list[4] + list[8] == 3:
alternative1 = True
elif list[0] + list[4] + list[8] == -3:
alternative2 = True
elif list[2] + list[4] + list[6] == 3:
alternative1 = True
elif list[2] + list[4] + list[6] == -3:
alternative2 = True
那么如何才能使这段代码更高效/更短?我想我可以通过某种while循环或类似的东西来实现这一点,但我不能让列表占位符匹配。
答案 0 :(得分:3)
一些一般性建议:
board={}
然后board[2,2]
,其中键是元组。为了使这更具体,让我们假设这是标准的井字游戏,并考虑如何检测胜利,这似乎是至少部分代码的目标。我们将使用2-D数组,1, 0, -1
意味着X, empty, O
正如您所做的那样(尽管您的特定编码可能不同)。
# List of winning combos.
win_runs = [
((0,0), (0,1), (0,2)), # ... rows
((0,0), (1,0), (2,0)), # ... columns
((2,0), (1,1), (0,2)), # ... diagonals
]
# Initialize empty board.
board = {(i,j): 0 for i in range(3) for j in range(3)}
# Set up a win in leftmost column.
board[0,0] = board[1,0] = board[2,0] = -1
# Check if anyone has a win.
for run in win_runs:
values = {board[tup] for tup in run} # values is a set
if len(values) == 1 and 0 not in values:
print('{} wins'.format(values.pop()))
break
else: # executed only if for loop is exhausted
print('no one wins yet')