繁体   English   中英

如何创建空 3D 数组(字符串)以及如何更新特定索引的值?

[英]How to create empty 3D array (string) and how to update the value for a specific index?

我试图创建一个 3D 阵列(8,15,8)。 我设法创建了数组,但是如何在特定索引处分配值?

收到这些消息:

文件“G:\Min enhet\Python\Travscript.py”,第 41 行,在 start_list_array[int(1),int(1),int(1)]=attribute.strip()

TypeError:列表索引必须是整数或切片,而不是元组

我的代码:

start_list_array = []
for i in range(8): 
    start_list_array.append([])
    for j in range(15):
        start_list_array[i].append([])
        for k in range(8):
            start_list_array[i][j].append([])
               
line_count = 0
race_count = 0
horse_count = 0
attribute_count = 0
for line in input:
    line_count += 1
    if line.strip() in spelformer:
        race_count =+ 1 
     
    elif line_count == 5:
        horse_count += 1

        for attribute in line.split('\t'):
            attribute_count =+ 1
            print(line_count)
            print(race_count)
            print(attribute_count)
            #start_list_array[int(race_count-1), int(horse_count-1), int(attribute_count-1)] = attribute.strip()
            start_list_array[int(1),int(1),int(1)]=attribute.strip()
            print("check2")
            print(start_list_array[int(race_count-1), int(horse_count-1), int(attribute_count-1)])

提前致谢。

Python 中的香草列表需要这样访问:

start_list_array[1][1][1]

The __get_item__ method in Python is implemented separately for each class and while other objects such as numpy arrays or pandas DataFrames may have implementations that support tuples, the list object does not.

事实上,您的顶级列表与其内部的内容无关,因为它知道它可能是字符串或不同长度的列表。

可以使用嵌套列表推导来声明多维列表。

arr = [[[0 for i in range(8)] for j in range(15)] for k in range(8)]

并且可以使用 arr[0][0][0] 引用/分配值

    arr = [[[0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0], ...
    arr[0] = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 
0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
    arr[0][1] = [0, 0, 0, 0, 0, 0, 0, 0]
    arr[0][0][1] = 0
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM