Store histograms in a large array depending on location in for loop

459 views Asked by At

I'm trying to store histograms in an array full of nested arrays that are created in multiple for a loop.

The error that I am getting is that: 'TH1F' object has no attribute 'append'

Here's an example of how the code works (a simplified version):

hist = []
for c in range 2:  
  hist.append([])

  for e in range 4: 
    hist[c].append([])
    hist_m = ROOT.TH1F("some name","some name",0,0.0,50.0)
    hist[c][e].append(hist_m)

    for z in range 8:
      hist[c][e].append([])
      hist_m = ROOT.TH1F("some name","some name",0,0.0,50.0)
      hist[c][e][z].append(hist_m)  #crashes here

      for pT in range 32:
        hist[c][e][z].append([])
        hist_m = ROOT.TH1F("some name","some name",0,0.0,50.0)
        hist[c][e][z][pT].append(hist_m)

I'm trying to store all of these different histograms inside of this large array so that I can use them later in the code by simply using the index. But I am getting the error

'TH1F' object has no attribute 'append'

which I don't know how to fix. Any solutions?

The code crashes on this line:

hist[c][e][z].append( hist )

Thanks in advance!

1

There are 1 answers

3
Wim Lavrijsen On BEST ANSWER

Here, and in other places, you're overwriting your hist variable that otherwise points to the large "array" you're building:

hist = ROOT.TH1F("some name","some name",0,0.0,50.0)

Use a different name ...

EDIT: since you now changed the naming, consider that you first add a TH1F:

hist[c][e].append(hist_m)

and afterwards a fresh list:

hist[c][e].append([])

so now the first element of list hist[c][e] is a TH1F, the second is a new list. Ie., you have:

[[[<ROOT.TH1F object ("some name") at 0x556fd65038d0>, []]]]

and zero indexing (c == e == z == 0) selects that TH1F.

The data structure as you seem to envision (an indexing being both a histogram if no further indexing happens, but a list if it does), isn't going to work. (Granted, you can add a __getitem__ method to the TH1F class to return a list, but that'd be a rather odd thing to do.)

If you want to have a large, indexable, "array" of histograms, those histograms will all have to be on the final leaf nodes.