用于操作嵌套列表的函数

2024-10-02 02:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

我获得:

an star of size 6

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)中的结果出乎我意料。我为什么得到它们?你知道吗


Tags: ofthe函数inforsizedefrange
2条回答

正如Ilja Everilä在注释中强调的,您的数组tablero包含同一数组col的X个副本,但这是一个引用副本,而不是值副本。因此,每次修改tablero中的一列时,更改都会出现在每一列中。你知道吗

解决方案是按值复制col。改变一下:

tablero.append(col)

收件人:

tablero.append(col[:])

第3点)中的问题是,当重复该函数时

construir_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)

def construir_tablero():
    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)

解决了这个问题,因为它在每个调用中重新定义了tablero。你知道吗

相关问题 更多 >

    热门问题