如何动态创建三维数组

2 投票
3 回答
4110 浏览
提问于 2025-04-17 02:10

如果我想要一个数组,比如:

[
    [
        [6,3,4],
        [5,2]
    ],
    [
        [8,5,7],
        [11,3]
    ]
]

我给你一个简单的例子。实际上,每个维度的数组数量会根据不同的条件而变化。我不想用列表的乘法来创建数组。我想直接创建每一个元素。

该怎么做呢?

谢谢!

3 个回答

-2

嗯,基本上就是你想的那样。在Python里,它们叫做列表,而不是数组,不过你只需要一个三层嵌套的列表,比如说,

threeDList = [[[]]]

然后你用三个索引来找到元素,比如说,

threeDList[0][0].append(1)
threeDList[0][0].append(2)
#threeDList == [[[1,2]]]
threeDList[0][0][1] = 3
#threeDList == [[[1,3]]]

你只需要注意,每个你用的索引都要指向列表中已经存在的位置(也就是说,在这个例子里,threeDList[0][0][2] 或 threeDList[0][1] 或 threeDList[1] 是不存在的),而且尽量使用列表推导式或者for循环来操作列表中的元素。

希望这对你有帮助!

1

在这种情况下,我通常会使用字典:

def set_3dict(dict3,x,y,z,val):
  """Set values in a 3d dictionary"""
  if dict3.get(x) == None:
    dict3[x] = {y: {z: val}}
  elif dict3[x].get(y) == None:
    dict3[x][y] = {z: val}
  else:
    dict3[x][y][z] = val

d={}    
set_3dict(d,0,0,0,6)
set_3dict(d,0,0,1,3) 
set_3dict(d,0,0,2,4)
...

就像我有一个获取器一样

def get_3dict(dict3, x, y, z, preset=None):
  """Read values from 3d dictionary"""
  if dict3.get(x, preset) == preset:
    return preset
  elif dict3[x].get(y, preset) == preset:
    return preset
  elif dict3[x][y].get(z, preset) == preset:
    return preset
  else: return dict3[x][y].get(z)

>>> get3_dict(d,0,0,0)
 6
>>> d[0][0][0]
 6
>>> get3_dict(d,-1,-1,-1)
 None
>>> d[-1][-1][-1]
 KeyError: -1

我认为使用字典的好处在于,遍历字段非常简单:

for x in d.keys():
  for y in d[x].keys():
    for z in d[x][y].keys():
      print d[x][y][z]
6

使用一个映射,把你的多维索引和对应的值联系起来。不要用一堆嵌套的列表。

array_3d = {
    (0,0,0): 6, (0,0,1): 3, (0,0,2): 4,
    (0,1,0): 5, (0,1,1): 2,
    (1,0,0): 8, (1,0,1): 5, (1,0,2): 7,
    (1,1,0): 11,(1,1,1): 3 
}

这样你就不需要担心提前分配什么大小、维度数量之类的问题了。

撰写回答