为什么python中的这个append函数没有';不行吗? def random_行(线路板,长度): 返回randint(0,长度(板)-长度) def随机_列(板,长度): 返回randint(0,len(板[0])-长度) ship_all=[] 对于范围(1,6)内的长度: 船舶=[] 船行=随机行(板,长度) ship.append(ship\u行) ship_col=随机_col(板,长度) ship.append(ship\u col) i=0 如果randint(0,1)=0: 虽然i
您没有将为什么python中的这个append函数没有';不行吗? def random_行(线路板,长度): 返回randint(0,长度(板)-长度) def随机_列(板,长度): 返回randint(0,len(板[0])-长度) ship_all=[] 对于范围(1,6)内的长度: 船舶=[] 船行=随机行(板,长度) ship.append(ship\u行) ship_col=随机_col(板,长度) ship.append(ship\u col) i=0 如果randint(0,1)=0: 虽然i,python,Python,您没有将ship的副本添加到ship\u all,但您正在一次又一次地添加相同的列表对象,每次迭代都会更改该对象 每次追加时都要创建一个: def random_row(board, length): return randint(0, len(board) - length) def random_col(board, length): return randint(0, len(board[0]) - length) ship_all = [] for length
ship
的副本添加到ship\u all
,但您正在一次又一次地添加相同的列表对象,每次迭代都会更改该对象
每次追加时都要创建一个:
def random_row(board, length):
return randint(0, len(board) - length)
def random_col(board, length):
return randint(0, len(board[0]) - length)
ship_all = []
for length in range(1,6):
ship = []
ship_row = random_row(board, length)
ship.append(ship_row)
ship_col = random_col(board, length)
ship.append(ship_col)
i = 0
if randint(0,1) == 0:
while i<length:
ship_all.append(ship)
ship[0] += 1
print ship
i+=1
else:
while i<length:
ship_all.append(ship)
ship[1] += 1
print ship
i+=1
print ship_all
或者在
while
循环中从头开始创建ship
列表。因为您正在使用对同一列表的多个引用填充ship\u all
。移动ship=[]
到循环中,同时循环。谢谢!它解决了,但是为什么,ship[:]
代表什么?@Liye:它通过从开始到结束切片列表,复制所有元素来创建副本。您也可以使用list(ship)
。
ship_all.append(ship[:])