在Python中创建N*N*N列表时出现问题
我正在尝试在 Python 中创建一个 3 维 NNN 列表,如下所示:
n=3
l = [[[0,]*n]*n]*n
不幸的是,这似乎并没有像我想象的那样正确“克隆”列表:
>>> l
[[[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, 0, 0]]]
>>> l[0][0][0]=1
>>> l
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]
我是什么这里做错了吗?
I'm trying to create a 3-dimensional NNN list in Python, like such:
n=3
l = [[[0,]*n]*n]*n
Unfortunately, this does not seem to properly "clone" the list, as I thought it would:
>>> l
[[[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, 0, 0]]]
>>> l[0][0][0]=1
>>> l
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题在于
* n
对列表进行了浅表复制。解决方案是使用嵌套循环,或尝试 numpy 库。The problem is that
* n
does a shallow copy of the list. A solution is to use nested loops, or try the numpy library.如果你想用 3 维矩阵进行数值处理,你最好使用 numpy。这很容易:
If you want to do numerical processing with 3-d matrix you are better of using numpy. It is quite easy:
正如其他人提到的,它是使用参考而不是克隆来构建第二层和第三层。尝试:
或者如果您想少输入一点:
As others have mentioned, it's building the 2nd and 3rd levels with references, not clones. Try:
Or if you want to type a bit less:
它不是克隆列表。它一遍又一遍地插入对同一列表的引用。尝试使用一组嵌套的 for 循环创建列表。
It's not cloning the list. It's inserting a reference to the same list over and over. Try creating the list using a set of nested for loops.
我必须赞同 leonardo-santagada 的建议,另外,创建 N 维数组/列表是非常不Pythonic的,你应该重新考虑如何保存你的数据,看看它是否不适合更好地属于一个类或一个列表字典(或列表字典)。
I have to second what leonardo-santagada suggested, with the addition that creating N dimensional arrays/lists is very unpythonic and you should reconsider how you're keeping your data and seeing if it doesn't belong better in a class or a list of dictionaries (or dictionaries of lists).