刚看了一位网友提出的问题:
我想建一个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]]
小技巧,记录一下,嗯
本文通过两种方式创建5×5列表,并对比分析了它们的区别。一种方式直接定义,另一种使用列表乘法。后者虽然简洁但存在赋值时所有子列表被同步修改的问题。文章介绍了正确的创建独立子列表的方法。
1467

被折叠的 条评论
为什么被折叠?



