【发布时间】:2015-11-22 02:19:57
【问题描述】:
我有一个
list = [value, 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 循环或类似的方法来完成此操作,但我无法让列表占位符匹配。
【问题讨论】:
-
这是列、行和对角线,不是吗?某种井字游戏?
-
for index1, index2, index3 in [(0, 1, 2), ...]: if list[index1] + list[index2] + list[index3] == mul: ...?并且不要影响list。 -
是的,实际上是一个非常相似的问题。 @德尔根
-
不要命名
list,因为那是内置类型的名称。 -
我投票结束这个问题,因为它要求对工作代码进行代码审查,这更适合codereview.stackexchange.com
标签: python python-3.x optimization