如何创建多维列表 [英] How to create a multi-dimensional list
问题描述
我想初始化一个多维列表.基本上,我想要一个10x10的网格-10个列表的列表,每个列表包含10个项目.
I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items.
每个列表值都应初始化为整数0.
Each list value should be initialized to the integer 0.
单行执行此操作的明显方法是: myList = [[0] * 10] * 10
不起作用,因为它会产生一个包含10个引用的列表,因此一个列表更改任何行中的一项都会更改所有行中的项.
The obvious way to do this in a one-liner: myList = [[0]*10]*10
won't work because it produces a list of 10 references to one list, so changing an item in any row changes it in all rows.
我看过的文档讨论了使用 [:]
复制列表的方法,但是在使用乘数时仍然无法使用: myList = [0] * 10;myList = myList [:] * 10
与 myList = [[0] * 10] * 10
具有相同的效果.
The documentation I've seen talks about using [:]
to copy a list, but that still won't work when using the multiplier: myList = [0]*10; myList = myList[:]*10
has the same effect as myList = [[0]*10]*10
.
创建 myList.append()
s循环的捷径,有没有一种快速有效的方法来以此方式初始化列表?
Short of creating a loop of myList.append()
s, is there a quick efficient way to initialize a list in this way?
推荐答案
使用 查看全文