Reputation: 3782
I have a feeling that there is a simple answer to this question, but I am having trouble getting the answer without having to write many many lines of code. I was hoping someone may give me something that will make my life easier in regards to list comprehensions in python.
What I have is this:
highest_peak = sorted([(self.Y[x]-self.background_model[x]) for x in peaks_index_list])[0]
How do I obtain the index (x) of the highest_peak from the peaks_index_list where this occurs?
index_of_highest_peak = sorted(???)[0]
index_of_second_highest_peak = sorted(???)[1]
Thanks for any help.
Upvotes: 1
Views: 171
Reputation: 77407
(note: edited based on comments)
Add the index to the objects being sorted:
highest_peak, index = sorted([(self.Y[x]-self.background_model[x], x)
for x in peaks_index_list])[0]
(originally I suggested using enumerate(), which is great when you want the index of the elements you are enumerating. In this case, the peaks_index_list is already the index the poster was after.)
highest_peak, index = sorted([(self.Y[x]-self.background_model[x], i)
for i, x in enumerate(peaks_index_list]))[0]
Upvotes: 2
Reputation: 77187
I take it the peak height is self.Y[i] - self.background_model[i]
for a peak index i
? If all you want is the index of the highest peak:
max(peaks_index_list, key=lambda i: self.Y[i] - self.background_model[i])
Likewise, if you really want the sorted list, use the above key to sort peaks_index_list
.
Upvotes: 3
Reputation: 20373
If you use numpy you can
import numpy as np
highest_peak = np.asarray(highest_peak)
max_index = highest_peak.argmax()
Upvotes: 3
Reputation: 310287
You should be sorting a list of tuples of the form (value,index) --
info = sorted((self.Y[x]-self.background_model[x],x) for x in peaks_index_list)
Now your index of the highest peak is:
info[-1][1]
Or you can unpack it a little more nicely:
highest_peak_value,highest_peak_index = info[-1]
(highest peak is last in the sorted list since we didn't specify reverse=True
)
The second highest peak index is:
info[-2][1]
and so on.
Upvotes: 2