T
tkpmep
I have an ordered list e.g. x = [0, 100, 200, 1000], and given any
positive integer y, I want to determine its appropriate position in
the list (i.e the point at which I would have to insert it in order to
keep the list sorted. I can clearly do this with a series of if
statements:
if y<x[1]:
n = 0
elif y < x[2]:
n = 1
elif y < x[3]:
n = 2
else:
n = 3
Or with a generator comprehension
n = sum ( y>x for i in range(len(x)) ) - 1
But there has to be a cleaner way, as the first approach is unwieldy
and does not adapt to changing list lengths, and the second is not
obvious to a casual reader of the code.
My list will typically have 2 to 5 items, so speed is not a huge
issue. I'd appreciate your guidance.
Sincerely
Thomas Philips
positive integer y, I want to determine its appropriate position in
the list (i.e the point at which I would have to insert it in order to
keep the list sorted. I can clearly do this with a series of if
statements:
if y<x[1]:
n = 0
elif y < x[2]:
n = 1
elif y < x[3]:
n = 2
else:
n = 3
Or with a generator comprehension
n = sum ( y>x for i in range(len(x)) ) - 1
But there has to be a cleaner way, as the first approach is unwieldy
and does not adapt to changing list lengths, and the second is not
obvious to a casual reader of the code.
My list will typically have 2 to 5 items, so speed is not a huge
issue. I'd appreciate your guidance.
Sincerely
Thomas Philips