我想在Python中构建一个多维列表,其中维度的数量在编写时(开发时)是未知的,但在运行时动态确定。
示例:如果我想创建一个n维网格,其中每个网格点对应于我创建的对象。 在这里,我想知道程序运行时改变n的算法。
答案 0 :(得分:0)
纯Python解决方案:
n = 2
f = [[0.0 for _ in range(2)] for _ in range(3)]
f[0][0] = 8
print (f)
n = 3
f = [[[0.0 for _ in range(2)] for _ in range(3)] for _ in range(3)]
f[0][0][0] = 5
print (f)
numpy
解决方案:
快速入门教程:array-creation
n = 2
f = np.zeros((2, 3,))
n = 3
f = np.zeros((2, 3, 3))
输出:
[[8,0.0],[0.0,0.0],[0.0,0.0]]
[[[5,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.0 ,0.0],[0.0,0.0]]]