刚看了一位网友提出的问题:
我想建一个5×5的列表,用以下两种方法:
(1)
>>> a
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
>>> a
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0], [0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
(2)
>>> a[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> a[2][3]=3
>>> a
[[0, 0, 0, 3, 0], [0, 0, 0, 3, 0], [0, 0, 0, 3, 0], [0, 0, 0, 3, 0],
[0, 0, 0, 3, 0]]
你知道的第二种创建方法更简洁一点,但是在赋值的时候出现了问题,有什么解决方法吗?(
#################################################
引自官方tutorial
consider:
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
What has happened is that [[]] is a one-element list containing an
empty list, so all three elements of
[[]] * 3 are (pointers to) this single empty list. Modifying any of
the elements of lists modifies this
single list. You can create a list of different lists this way:
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
小技巧,记录一下,嗯