【发布时间】:2018-11-21 02:17:34
【问题描述】:
我有这个方法可以从棋盘上获取所有有效的移动。
def get_all_moves(self) -> list:
moves = []
pieces = self.__get_all_turn_pieces()
for p in pieces:
self.__jump_moves(p.coord, moves)
self.__b.wipe()
self.__simple_moves(p, moves)
moves.sort(key=len, reverse=True)
for i in range(len(moves)):
for j in range(len(moves)):
if moves[i][:len(moves[j])] == moves[j] and len(moves[i]) > len(moves[j]):
moves.remove(moves[j])
return moves
问题是:根据跳棋规则,玩家必须在他的移动中执行最多数量的捕获。因此我需要删除无效的动作。
让我们分析这个输出:
[[3, 0, 5, 2, 3, 4], [5, 0, 3, 2, 5, 4], [1, 0, 2, 1], [1, 2, 2, 3], [1, 2, 2, 1], [1, 4, 2, 3], [2, 5, 3, 6], [2, 5, 3, 4], [2, 7, 3, 6], [3, 0, 5, 2], [5, 0, 3, 2]]
输出列表的第一项和第二项分别包含最后两项。所以我需要删除它们,因为它们是第一个的“子列表”。
问题是我的嵌套循环不能解决这个问题。程序溢出这个错误:
Traceback (most recent call last):
File "damas.py", line 435, in <module>
print(m.get_all_moves())
File "damas.py", line 418, in get_all_moves
if moves[i][:len(moves[j])] == moves[j] and len(moves[i]) > len(moves[j]):
IndexError: list index out of range
过了一会儿,我想知道解决这个问题最pythonic的方法是什么。
【问题讨论】:
标签: python-3.x list