Problems with the way of generating matrices...

30/06/2008 - 08:39 von Thomas Lehmann | Report spam
Hi,

is this a bug or an issue?
I'm creating matrices in two ways.
The first two prints are showing the same!
After that, accessing the two matrices the
same way the next two prints differ (see output)!
Why?

best regards,
Thomas

matrix_a = [[0] * 3] * 3
print matrix_a

matrix_b = [[0,0,0], [0,0,0], [0,0,0]]
print matrix_b

assert matrix_a == matrix_b
print

matrix_a[1][1] = 1
print matrix_a

matrix_b[1][1] = 1
print matrix_b

output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
 

Lesen sie die antworten

#1 Thomas Rachel
30/06/2008 - 09:21 | Warnen spam
Thomas Lehmann schrieb:

The first two prints are showing the same!



Aber nur scheinbar.


After that, accessing the two matrices the
same way the next two prints differ (see output)!
Why?



Weil Du in einem Fall dieselben Objekte mehrfach in der Liste hast, und
im anderen Fall drei verschiedene.

matrix_a = [[0] * 3] * 3
print matrix_a


print [id(i) for i in matrix_a]

matrix_b = [[0,0,0], [0,0,0], [0,0,0]]
print matrix_b


print [id(i) for i in matrix_b]


Dann siehst Du, daß bei a) dasselbe Objekt [0,0,0] dreimal im Array
landet, wàhrend bei b) drei zunàchst gleichwertige, aber
unterschiedliche Objekte erzeugt werden.

matrix_a[0] is matrix_a[1] is matrix_a[2]
-> True

matrix_b[0] is matrix_b[1] is matrix_b[2]
-> False

HTH,

Thomas

Ähnliche fragen