Reputation: 79
I am populating a multi-dimensional (2D) list of NamedTuple structures, like this:
from typing import NamedTuple
class Halo(NamedTuple):
ID: int
axis: str
event_file: str
I declare an empty 2D list:
halo_arr = [[[] for i in range(nhalo_bins)] for j in range(nperbin)]
I then populate the list with the above individual structures in a loop:
my_item = Halo(int(IDarr_shuf[j][i]), axis_arr[j], evt_file)
halo_arr[nhalos[hbin]][hbin] = my_item
I am able to fill this 2D list with the tuple structure, and access individual elements:
e.g.
print(halo_arr([0][5].ID))
but I want to be able to access the entire array of IDs (or any other array of the tuple):
e.g.
print(halo_arr.ID)
so that I can put that entire 2D array as a dataset into an hdf5 file:
e.g.
fh5.create_dataset("/Halos/IDs",data=halo_arr.ID)
Yet, I get this error:
print(halo_arr.ID)
AttributeError: 'list' object has no attribute 'ID'
I'm at a loss here, and may not be using the optimal structure.
Upvotes: 0
Views: 696
Reputation: 42143
Accessing an individual property inside that list of lists would require a more explicit expression of how to access the tuples depending on what you need as output. For example using list comprehensions:
[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
The first one (flat list) is equivalent to:
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, ...]
The second one (2D) is equivalent to:
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, ...]
# ... ]
Upvotes: 1