6

我正在尝试在战舰板上设置船只。下面代码中的函数应该使用许多船和一个板(数组数组)作为参数来执行此操作。当我在终端中运行它时,我得到:

[[1, [...]], [1, [...]], [2, [...]]]

这是什么意思?如何在此输出中用 0 到 2 的随机整数替换 [...]?

from random import randint

def print_board(board):
    for row in board:
        print " ".join(row)
def random_row(board):
    return randint(0, len(board) - 1)
def random_col(board):
    return randint(0, len(board[0]) - 1)

def set_the_ships(num_ships,board):
    ship_list = []
    for i in range(num_ships):
        ship_row = random_row(board)
        ship_col = random_col(board)    
        position = [ship_row,ship_list]
        for j in range(i - 1):
            while (position[0] == ship_list[j][0] and position[1] == ship_list[j][1]):
                ship_row = random_row(board)
                ship_col = random_col(board)    
                position = [ship_row,ship_list]
        ship_list.append(position)
    return ship_list

print set_the_ships(3,[[0,0,0],[0,0,0],[0,0,0]])
4

2 回答 2

3

...意味着,有参考周期。

>>> l = []
>>> l.append(l)
>>> l
[[...]]
于 2013-10-21T14:50:38.900 回答
2

看到这一行:

position = [ship_row,ship_list]

这应该是

position = [ship_row,ship_col]

(当您重新分配position in thewhile` 循环时相同)

稍后,当您这样做时ship_list.append(position),这会导致ship_list嵌套在自身中,Python 将其打印为[...].

于 2013-10-21T14:53:06.423 回答