Comparison, exclusion, and popping elements from a list (Python) -
i want compare number (dist) against each element of sorted list (my list).
if number smaller first element in mylist, have proceed , find right place dist, eliminate first element in mylist , shift list.
my main problem tha case when dist smaller 1st elemnt in mylist. index out of range ...
dist = 10 mylist = [40, 30, 20, 15] # sorted list j in range(0, len(mylist)): if mylist[j] < dist & dist> mylist[j+1]: print (mylist[j], '<' ,dist, '>', mylist[j+1]) #drop 40 #shift list becomes: [30,20, 15,10]
iiuc, want insert dist @ right position , knock off first element. fine, have few issues. major 1 being condition, , i'm not talking &. you'll want make sure dist greater current, lesser next. this:
if mylist[j] < dist < mylist[j+1]: you'll have run till 1 lesser len(mylist) avoid index out of bounds.
another trick can use for...else work corner case dist not inserted anywhere else.
in short, try this:
for j in range(len(mylist) - 1): if mylist[j] < dist < mylist[j + 1]: mylist.insert(j, dist) mylist = mylist[1:] break else: mylist.append(dist) mylist = mylist[1:] alternatively, can run 1 len(mylist), , compare check mylist[j - 1] < dist < mylist[j].
Comments
Post a Comment