初始化矩阵python3

时间:2013-09-22 16:15:40

标签: python-3.x matrix initialization

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

>>> 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__令牌的错误语义?

1 个答案:

答案 0 :(得分:1)

您多次将相同的引用复制到列表中。这样做:

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