开发者

How to dynamically create a three-dimensional array

开发者 https://www.devze.com 2023-04-04 05:05 出处:网络
If I want to a array, for example: [ [ [6,3,4], [5,2] ], [ [8,5,7], [11,3] ] ] And I just give you a simple example. In fact, the number of array of each dimensional will be changed with differ开发

If I want to a array, for example:

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

And I just give you a simple example. In fact, the number of array of each dimensional will be changed with differ开发者_运维问答ent conditions. And I don't want to use multiplication of list. I want to create every element directly.

How to do it?

Thank you!


Use a mapping from your multi-dimensional index to your values. Don't use a list of lists of lists.

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 
}

Now you don't have to worry about "pre-allocating" any size or or number of dimensions or anything.


I take dictionaries all the way for such cases:

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)
...

In anology I have a getter

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

In my opinion the advantage lies in iterating over the field being quite simple:

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


Um, pretty much the way you'd think. In Python they're called lists, not arrays, but you just have a triple-nested list, like,

threeDList = [[[]]]

and then you use three indices to identify elements, like

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

You just have to be careful that every index you use refers to a place in the list that already exists (i.e. threeDList[0][0][2] or threeDList[0][1] or threeDList[1] does not exist in this example), and when possible, just use comprehensions or for loops to manipulate the elements of the list.

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消