Txus Lopez
Txus Lopez

Reputation: 77

Sort a list, but leave a specified value in place

I need to use the numpy.argsort function (or a code that makes the same) but ignoring a concrete value, for example -1, and keeping it in the resulted array

If this is the list: [5,8,1,-1,2,4], I need a result like [3,4,0,-1,1,2]

How can I do it?

Upvotes: 0

Views: 905

Answers (2)

Txus Lopez
Txus Lopez

Reputation: 77

mylist=[5,8,1,-1,2,4]
print 'mylist: ',mylist
ignored=[]
new_my_list=[]

for i in range(len(mylist)):
    if mylist[i]==-1:
        ignored.append((i,mylist[i]))
    else:
        new_my_list.append(mylist[i])

print 'new_my_list without -1: ',new_my_list

mylist_sorted=list(np.argsort(new_my_list))

print 'mylist_sorted: ',mylist_sorted

temp_orders=list(np.zeros(len(mylist_sorted)))
for fr in range(len(mylist_sorted)):
            idx=mylist_sorted[fr]
            temp_orders[idx]=fr

print 'temp_orders: ',temp_orders

for ig in range(len(ignored)):
    ig_add=ignored[ig]
    temp_orders.insert(ig_add[0], ig_add[1])

print 'new_my_list with -1: ',temp_orders

One improvement to the last loop:

for ig_idx, ig_value in ignored):
    temp_orders.insert(ig_idx, ig_val)

Upvotes: 1

Prune
Prune

Reputation: 77857

Locate and remove each of the values to ignore, remembering their positions. For instance, in this case, you might store the index and value as ignore = (3, -1).

Sort the remaining list as usual.

Reinsert the missing element: mylist.insert(ignore[0], ignore[1])

Does that get you moving?

Upvotes: 2

Related Questions