Python:初始化多维列表 [英] Python: initialize multi-dimensional list

查看:1019
本文介绍了Python:初始化多维列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想初始化一个多维列表.基本上,我想要一个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[:]*10myList = [[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?

推荐答案

使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆