rooms
rooms

Reputation: 300

Summing sliced list using arrays of indices

I have an array of indices of the form

 b1c_loc= [
    (1843, 1854, 63),
    (32144, 32155, 56),
    (32516, 32556, 71),
    (32589, 32600, 60),
    (34081, 34092, 66),
    (35600, 35611, 67),
]

The first two columns are indices corresponding to a list that I want to sum between. The last column is just there for book keeping because it corresponds to a real world application.

Now I also have a list called Ehisto. I want to sum over each index range as shown in the rows of b1c_loc, as in b1c_loc[0][0] to b1c_loc[0][1] all the way down for every row for Ehisto, and append the corresponding summation to each row, something of the form:

[index1, index2, label, Sum between index1 and index2 in Ehisto]

or, with placeholder numbers,

 [
    (1843, 1854, 63, 1),
    (32144, 32155, 56, 2),
    (32516, 32556, 71, 3),
    (32589, 32600, 60, 4),
    (34081, 34092, 66, 5),
    (35600, 35611, 67, 6),
]

This was my attempt at doing this:

for s in b1c_loc:
    np.append(sum([Ehisto[s[0]]:Ehisto[s[1]]]))

I wanted to sum a slice of Ehisto using the indices stored in b1c_loc. This doesn't work. Instead I get an error

In [37]: for s in b1c_loc:
   ....:         np.append(sum([Ehisto[s[0]]:Ehisto[s[1]]]))
   ....:     
  File "<ipython-input-37-b0e7c475a95d>", line 2
    np.append(sum([Ehisto[s[0]]:Ehisto[s[1]]]))
                               ^
SyntaxError: invalid syntax

Have I gone about doing this in completely the wrong way? It seems quite simple, and I don't feel like I've done anything crazy but this error shows up. Anyway, sorry if this question isn't worded so well. I'm really quite new to python and I'm still learning. Thanks in advance for any help

Upvotes: 1

Views: 87

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

If you want to access the first and second elements of each tuple just unpack:

b1c_loc= [
    (1843, 1854, 63),
    (32144, 32155, 56),
    (32516, 32556, 71),
    (32589, 32600, 60),
    (34081, 34092, 66),
    (35600, 35611, 67),
]   

print([b - a for a, b, _ in b1c_loc])
[11, 11, 40, 11, 11, 11]

for a, b, _ in b1c_loc unpacks the three subelements from each tuple using _ for the third element as we do not plan to use it. We then just subtract a from b.

So if you want to use those values to access elements in Ehisto list by indexing we can again use a list comprehension using the same logic:

res = [sum((Ehisto[a], Ehisto[b])) for a, b, _ in b1c_loc]

Your code fails as you separate values with a colon when you should be using a comma ,.

np.append(sum([Ehisto[s[0]], Ehisto[s[1]]]))

On a side note use lowercase for variable names ehisto etc..

Upvotes: 3

Related Questions