python - 在python中插入3d数组

标签 python arrays list exception insert

我在尝试插入 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 - 在python中插入3d数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334113/

相关文章:

java - 从数组中找到元素的最低绝对总和

arrays - 如何将具有值的数组放入一列

javascript - 如何使用 ES6 方法将这个对象数组转换为字符串?

list - F# 9 名称分为 2、3 和 4 个不相交的组

c++ - 如何使用getter函数将列表推回列表?

Python 的闭包——赋值前引用的局部变量

python - 选择行和列特有的列表元素的列表(N 个皇后)

python - 如何将自己的索引添加到在 virtualenv 中运行的 pip?

python - 使用turtle.onscreenclick查找鼠标单击的坐标

以不确定长度作为参数的 R 函数列表