0

我不知道这是否是一个错误,或者我得到了数组中 * 标记的错误语义:

>>> arr = [None] * 5    # Initialize array of 5 'None' items
>>> arr
[None, None, None, None, None]
>>> arr[2] = "banana"
>>> arr
[None, None, 'banana', None, None]
>>> # right?
... 
>>> mx = [ [None] * 3 ] * 2     # initialize a 3x2 matrix with 'None' items
>>> mx
[[None, None, None], [None, None, None]]
>>> # so far, so good, but then:
... 
>>> mx[0][0] = "banana"
>>> mx
[['banana', None, None], ['banana', None, None]]
>>> # Huh?

__mult__这是一个错误,还是我得到了错误的令牌语义?

4

1 回答 1

1

您正在多次复制对列表的相同引用。像这样做:

matrix = [[None]*3 for i in range(2)]

于 2013-09-22T16:21:39.097 回答