2013-10-21 275 views
5

我试图在战舰上设置船只。下面的代码中的函数应该用一些船只和一个板(一个数组数组)作为参数来做到这一点。当我在终端中运行这个时,我得到:python中的输出是什么意思?

[[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]]) 

回答

3

...表示有参考周期。

>>> l = [] 
>>> l.append(l) 
>>> l 
[[...]] 
+0

“引用循环”表示列表包含对自身的引用。 – kindall

+2

不仅对于它本身,而且对于递归调用中已经打印的任何对象,请考虑例如:'a = []; B = [A]; a.append(b)中; C = [A];打印c' – lejlot

2

看到这一行:

position = [ship_row,ship_list] 

这应该是

position = [ship_row,ship_col] 

(同样,当你重新分配position in the while`环)

后来,当你做ship_list.append(position) ,这会导致ship_list本身嵌套,Python打印为[...]