1)如果我这样做:
tablero = [[' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', '
'], [' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' '], ['
', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ']]
def dibujar_cruz():
x = 0
a = "X"
size = len(tablero)
for row in tablero:
tablero[x][x] = a
tablero[x][size-x-1]=a
x += 1
for l in tablero:
print (" ".join(l))
dibujar_cruz()
我获得:
2)但是如果函数“dibujar_cruz()”从另一个函数获取初始嵌套列表,如下所示:
tablero =[]
def construir_tablero():
size =int(input("Which is the size of the nested lists? "))
col=[]
for x in range (size):
col .append(" ")
for b in range(size):
tablero.append(col)
return (tablero)
print (construir_tablero())
def dibujar_cruz():
x = 0
size = len(tablero)
for row in tablero:
row [x]= "X"
row[size-x-1]="X"
x += 1
for l in tablero:
print (" ".join(l))
dibujar_cruz()
我获得:
Square obtained calling the two functions consecutively
当我期望得到与第1点相同的星星时)。你知道吗
3)如果我定义了调用前两个函数的第三个函数:
def construir_cruz():
construir_tablero()
dibujar_cruz()
construir_cruz()
我希望得到与1)中相同的星,但我得到了一个错误:
... row[size-x-1]="X"
IndexError: list assignment index out of range
2)和3)中的结果出乎我意料。我为什么得到它们?你知道吗
正如Ilja Everilä在注释中强调的,您的数组
tablero
包含同一数组col
的X个副本,但这是一个引用副本,而不是值副本。因此,每次修改tablero
中的一列时,更改都会出现在每一列中。你知道吗解决方案是按值复制
col
。改变一下:收件人:
第3点)中的问题是,当重复该函数时
它的内存中已经有一个表。 将表格定义的位置从以下位置更改为:
至
解决了这个问题,因为它在每个调用中重新定义了tablero。你知道吗
相关问题 更多 >
编程相关推荐