[英]How to dynamically create a three-dimensional array
如果要数组,例如:
[
[
[6,3,4],
[5,2]
],
[
[8,5,7],
[11,3]
]
]
我只是给你一个简单的例子。 实际上,每个维度的阵列数将随着不同的条件而改变。 而且我不想使用列表的乘法。 我想直接创建每个元素。
怎么做?
谢谢!
使用从多维索引到值的映射。 不要使用列表列表。
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
}
现在,您不必担心“预分配”任何大小或数量的维度或任何其他内容。
对于此类情况,我会一律采用字典:
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]
嗯,你的想法差不多。 在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] [0] [2]或threeDList [0] [1]或threeDList [1]在其中不存在)此示例),并且在可能的情况下,只需使用理解或for循环即可操作列表中的元素。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.