DilithiumMatrix
DilithiumMatrix

Reputation: 18637

sort integers positive then negative

I have a dictionary of 'name': Obj entries, where each Obj has a num parameter that takes a signed integer. I want to convert this into an OrderedDict where the entries are sorted by positive Obj.num values, then negative numbers.

Sorting overall is no problem:

>>> data = OrderedDict(sorted(data.items(), key=lambda tt: tt[1].num))
>>> print([val.num for key, val in data.items()])
[-5, -2, -1, 1, 2, 10, 100]

But I want to end up with either:
[1, 2, 10, 100, -5, -2, -1]
or
[1, 2, 10, 100, -1, -2, -5]

How can I do this?

Upvotes: 1

Views: 771

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

reverse the sort, use x >= 0 to get the positive numbers first, - the numbers to put the negative numbers at the at the end and keep the order of positive from lowest to highest.

l = [-5, -2, -1, 1, 2, 10, 100]

print(sorted(l, key=lambda x: (x >= 0, -x), reverse=True))

For your dict:

OrderedDict(sorted(data.items(), key=lambda tt: (tt[1].num >= 0, -tt[1].num , reverse=True)))

Upvotes: 5

Related Questions