Python 3.5 - 如何使这段代码更高效/更短?

时间:2015-11-21 15:38:06

标签: python python-3.x optimization

我有一个

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循环或类似的东西来实现这一点,但我不能让列表占位符匹配。

1 个答案:

答案 0 :(得分:3)

一些一般性建议:

  • 当您的逻辑是数据而非代码时,代码通常 更清晰,更容易修改。构建将情境映射到操作的数据结构。 Jon Bentley的 Programming Pearls 详细介绍了这一点。
  • 您可以将dict用作二维数组: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')