簡體   English   中英

在python中插入3d數組

[英]inserting into a 3d array in python

我在嘗試插入3d數組時遇到類型錯誤:“ TypeError:'int'對象不可下標”。 我已經檢查並確認計數器工作正常(對於z計數器,x = -1是我在此處排除的較大循環的一部分)。 我想將字符串temp放在數組temp2的[0] [0] [0]中,迭代計數器並繼續添加到列表中,但是我顯然不知道該怎么做。 我是否需要以某種方式初始化temp2數組,當我不知道它應該有多大時該怎么做? 感謝您的幫助。

在程序頂部初始化:

temp2=[]
t=0
temp=""

這是引發異常的代碼

z=-1
for subtree in result.subtrees(filter=lambda t: t.node == 'Proper'):
    z=z+1
    y=0

    # this iterates through the actual subtree
    for p in subtree:
        temp = str(p[0])

        temp2.insert([t][z][y],temp)  #This line raises the exception
        y=y+1

#increments the first dimension of the array and resets the temp list      
t=t+1
temp = ""

您可能想要使用defaultdict這樣的

from collections import defaultdict
temp2 = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

temp2[t][z][y] = temp

例如:

from collections import defaultdict
temp2 = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
temp2[1][2][3] = 4
print temp2[1][2][3]

產量

4

我建議,如果您確實想要Python中的3D數組,請尋找已經有一個3D數組的庫(也許是numpy),或者編寫一個類,該類在構造函數中傳遞尺寸時會創建具有正確“形狀”的數組”。

否則,您可能會意外地得到衣衫“的“數組”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM