0

Python 2.7.3 - Debian 7 - 32 位

我正在尝试在列表(tabla )中添加列表( listado ) ,但是当打印tabla时, tabla中的所有元素都是相同的,而且它是添加的最后一个列表!!!!

tabla = []
listado = [0,0,0]    
lista_base = range(100)                       

for elemento in lista_base:
    listado[0] = elemento
    listado[1] = elemento+1
    listado[2] = elemento+2
    tabla.append(listado)       # <--- What is wrong here ??
    print(listado)              # <--- This works fine. It is print each *listado*.

print(tabla)                    
4

2 回答 2

1

您正在更改同一列表的内容,并在tabla. 因此, 中的所有列表tabla都将与最后list添加的相同。

您应该每次在循环中创建一个新列表。尝试将循环更改为:

for elemento in lista_base:
    listado = [elemento, elemento+1, elemento+2]
    tabla.append(listado)     
于 2013-08-10T11:08:37.230 回答
1

You are manipulating the same list over and over again, not a copy.

Create a new list in the loop instead:

for elemento in lista_base:
    listado = [elemento, elemento + 1, elemento + 2]
    tabla.append(listado)

or create a copy of the list:

for elemento in lista_base:
    listado[0] = elemento
    listado[1] = elemento+1
    listado[2] = elemento+2
    tabla.append(listado[:])

where [:] returns a full slice of all the elements. You could also use list(listado) or import the copy module and use copy.copy(listado) to create a copy of the existing list.

Appending a list to another list only adds a reference, and your code thus created many references to the same list that you kept changing in the loop.

You could have seen what was happening had you printed tabla on every loop. Printing listado on every loop iteration only shows that the state of that list was correct for that iteration, not that all the references to that list in tabla were changing along with it:

>>> tabla = []
>>> listado = [0, 0, 0]
>>> for elemento in range(3):
...     listado[0] = elemento
...     listado[1] = elemento+1
...     listado[2] = elemento+2
...     tabla.append(listado)
...     print 'tabla after iteration {}: {!r}'.format(elemento, tabla)
... 
tabla after iteration 0: [[0, 1, 2]]
tabla after iteration 1: [[1, 2, 3], [1, 2, 3]]
tabla after iteration 2: [[2, 3, 4], [2, 3, 4], [2, 3, 4]]

Notice how all tabla lists change together; they are in fact all the same list. If you create a new list instead, things work as expected:

>>> tabla = []
>>> for elemento in range(3):
...     listado = [elemento, elemento + 1, elemento + 2]
...     tabla.append(listado)
...     print 'tabla after iteration {}: {!r}'.format(elemento, tabla)
... 
tabla after iteration 0: [[0, 1, 2]]
tabla after iteration 1: [[0, 1, 2], [1, 2, 3]]
tabla after iteration 2: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
于 2013-08-10T11:08:30.737 回答