[英]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.