請,爲什麼這樣做Python的 - 如何解釋在這種情況下分配數據數組
array[0][0] = 'Tadaaaa'
改變5個元素,而不是一看到下面的代碼?
首先,創建一個空數組:
x, y = 5, 3
# when you multiply it's copying, so the ids of each item is the same
array = [[set()] * y] * x
array
我將獲得:
[[set(), set(), set()],
[set(), set(), set()],
[set(), set(), set()],
[set(), set(), set()],
[set(), set(), set()]]
然後將值分配給元素:
array[3][2].add('BBC')
array
我將獲得:
[[{'BBC'}, {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}]]
但是當我做:
array[0][0] = 'Tadaaaa'
array
我得到:
[['Tadaaaa', {'BBC'}, {'BBC'}],
['Tadaaaa', {'BBC'}, {'BBC'}],
['Tadaaaa', {'BBC'}, {'BBC'}],
['Tadaaaa', {'BBC'}, {'BBC'}],
['Tadaaaa', {'BBC'}, {'BBC'}]]
這是怎麼回事?
我想我會得到這樣的:
[['Tadaaaa', {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}],
[{'BBC'}, {'BBC'}, {'BBC'}]]
如果會發生什麼你做([0],[0])呢? – alex