在python中创建动态大小的多维列表

时间:2017-08-08 15:50:30

标签: python arrays multidimensional-array

我想在Python中构建一个多维列表,其中维度的数量在编写时(开发时)是未知的,但在运行时动态确定。

示例:如果我想创建一个n维网格,其中每个网格点对应于我创建的对象。 在这里,我想知道程序运行时改变n的算法。

1 个答案:

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