Reputation: 145
Given an array, say array = [3,5,-1,4,2,-1,5,0,-1]
, I want to sort it such that everything stays in the same place, except the -1's which will move to the end, so:
>>> function(array)
[3,5,4,2,5,0,-1,-1,-1]
This could also be generalised to any number, however, I'm using -1 as a key value and need them to all be at the end of the array for some later processing.
I've tried playing with the sort() and sorted() inbuilt functions in python however neither of these seemed to be able to do what I needed.
Upvotes: 1
Views: 928
Reputation: 36658
You can use a lambda function in your call to sort
. Here we sort the values by returning a 0 if the value is anything other than -1, otherwise 1. This will push all of the -1 values to the right.
array.sort(key=lambda x: x==-1)
array
# returns
[3, 5, 4, 2, 5, 0, -1, -1, -1]
Upvotes: 2
Reputation: 140226
Python sort
is stable, so you can just move some items around, leaving the others untouched
lst = [3,5,-1,4,2,-1,5,0,-1]
print(sorted(lst,key = lambda x : x == -1))
result: [3, 5, 4, 2, 5, 0, -1, -1, -1]
with this key, all items which are equal to -1
yield True
for the sort key, making them rise to the end of the list. Others are left where they are relatively to each other (because sort key yields the same False
value for all of them).
Upvotes: 1
Reputation: 82775
This is one approach.
Ex:
array = [3,5,-1,4,2,-1,5,0,-1]
num = -1
print([i for i in array if i != num] + [i for i in array if i == num])
Output:
[3, 5, 4, 2, 5, 0, -1, -1, -1]
Upvotes: 1