Is there a way to combine multiple list comprehensions in Python?

Viewed 66

Here's a function in my code:

def get_weights(Last_scan, Peak_shot):
    Est_Succshots = [x*Peak_shot for x in Last_scan.values()]
    Est_error = [np.sqrt(i)/Peak_shot for i in Est_Succshots]
    Is = [1/m for m in Est_error]
    Weights = [i/sum(Is) for i in Is]
    return Weights

I used 4 list comprehensions to do the calculation. I wonder is there a shorter way or a different approach I can perform such calculations? Thanks for the help:)

1 Answers

Assuming that Last_scan.values() is a list of numbers and Peak_shot is a number, this seems to be equivalent to

def get_weights(Last_scan, Peak_shot):
    Is =  np.sqrt(Peak_shot/np.array(Last_scan.values()))
    return Is/Is.sum()
Related