在Python中创建N * N * N列表时出现问题 [英] Problem creating N*N*N list in Python

查看:94
本文介绍了在Python中创建N * N * N列表时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中创建3维N N N列表,例如:

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]]]

我在做什么错了?

推荐答案

问题是* 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.

这篇关于在Python中创建N * N * N列表时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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