I have a got several list of numbers as output.i need to find the sum of all the corresponding first elements of all the lists(to find the average).
for i in fitsfiles:
hdul = fits.open (i)
flux= hdul[1].data['FLUX']
waves =hdul[1].data['WAVE']
from scipy.interpolate import interp1d
f = interp1d(waves,flux,fill_value='interpolate')
f_int = f(w_int)
intflux = f_int.tolist()
print(sum(intflux[0]))
I interpolated the parent data and the interpolated data is the output intflux. while doing the sum on this float im getting the error "TypeError: 'float' object is not iterable". Please help me how to find the average of all the corresponding elements of the list that comes as output
this is how my output looks like
CodePudding user response:
Given a list of lists list_of_lists
such as your output, you can use a python comprehension to iterate over the items in list_of_lists
generating the first element of each list, then call sum()
with this comprehension as its argument:
list_of_lists = [
[1.1, 1.2, 1.3],
[2.1, 1.2, 1.3],
[3.1, 1.2, 1.3],
[4.1, 1.2, 1.3],
[5.1, 1.2, 1.3],
[6.1, 1.2, 1.3]
]
sum_of_first = sum(x[0] for x in list_of_lists)
print(sum_of_first)
Output:
21.6
CodePudding user response:
The error occurs because intflux
is a specific output list (the last one generated in the loop) at any given time, rather than representing all of the output lists as a whole. Therefore intflux[0]
is the first element of a specific output list, rather than containing the first element of every output list.
You could store a list of all output lists, but if the only information you need is the sum or average, it may be simpler just to keep a running total, and add to it after generating each list:
running_total = 0
for i in fitsfiles:
...
running_total = intflux[0]
average = running_total / len(fitsfiles)
P.S. Try moving the line from scipy.interpolate import interp1d
to the start of your program. This makes your code faster and much more readable.