xyz-x
xyz-x

Reputation: 145

Sorting only a single value in an array

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

Answers (3)

James
James

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

Jean-François Fabre
Jean-François Fabre

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

Rakesh
Rakesh

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

Related Questions