首页 > 解决方案 > 如何访问元组的多维列表?

问题描述

我正在填充 NamedTuple 结构的多维 (2D) 列表,如下所示:

from typing import NamedTuple

class Halo(NamedTuple):
    ID: int
    axis: str
    event_file: str

我声明一个空的 2D 列表:

halo_arr = [[[] for i in range(nhalo_bins)] for j in range(nperbin)]

然后,我在循环中使用上述各个结构填充列表:

 my_item = Halo(int(IDarr_shuf[j][i]), axis_arr[j], evt_file)
 halo_arr[nhalos[hbin]][hbin] = my_item

我可以用元组结构填充这个二维列表,并访问单个元素:

例如

print(halo_arr([0][5].ID))

但我希望能够访问整个 ID 数组(或元组的任何其他数组):

例如

print(halo_arr.ID)

这样我就可以将整个二维数组作为数据集放入 hdf5 文件中:

例如

fh5.create_dataset("/Halos/IDs",data=halo_arr.ID)

然而,我得到这个错误:

print(halo_arr.ID)

AttributeError:“列表”对象没有属性“ID”

我在这里不知所措,可能没有使用最佳结构。

标签: pythonarrayslisttuples

解决方案


访问该列表列表中的单个属性将需要更明确地表达如何访问元组,具体取决于您需要作为输出的内容。例如使用列表推导:

[t.ID for row in halo_arr for t in row]   # if you want it flat

[[t.ID for t in row] for row in halo_arr] # if you want it 2D

第一个(平面列表)相当于:

result = list()
for row in halo_arr:         # Go through the first dimension (row is a list)
    for t in row:            # Go through tuples of the row
        result.append(t.ID)  # add ID to flat list

# result will be [id1, id2, id3, ...]

第二个(2D)相当于:

result = list()
for row in halo_arr:         # Go through the first dimension (row is a list)
    IDlist = list()          # prepare a row of IDs
    for t in row:            # Go through tuples of the row
        IDlist.append(t.ID)  # add to row of IDs
    result.append(IDlist)    # add row of IDs to result

# result will be [ [id1, id2, id3,  ...],
#                  [id8, id9, id10, ...]
#                  ... ]

推荐阅读