kesarling
kesarling

Reputation: 2238

sort a list according to keys and for elements with same keys as per values in python

I started learning python recently. I am trying to sort a list of lists similar to this. However, I'm not able to find the correct method to do so please help.

Consider the list [[1,4], [3,3], [3,2] ,[1,2], [1,3], [2,3], [1,5]]

now, using

def keyFunc(j):
        return j[0]

job = sorted(job, key=keyFunc, reverse=True)

I got it down to [[all 3s], [all 2s], [all 1s]]

However, now I want to further sort it so that the lists with common keys are in the order of descending values of their keys.

i.e. [[3,3], [3,2], [2,3], [1,5], [1,4], [1,3], [1,2]]

How does one do that in python?

Upvotes: 0

Views: 731

Answers (3)

Kelly Bundy
Kelly Bundy

Reputation: 27629

Why do you use a wrong key function when not using a key function already does what you want?

>>> sorted(job, reverse=True)
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]

Or since you're assigning back to job anyway, you might want to do job.sort(reverse=True) instead of creating a new list.

Upvotes: 2

RoadRunner
RoadRunner

Reputation: 26325

I think you can just negate the sorting keys to sort descending twice:

>>> lst = [[1,4], [3,3], [3,2] ,[1,2], [1,3], [2,3], [1,5]]
>>> sorted(lst, key=lambda x: (-x[0], -x[1]))
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]

(-x[0], -x[1]) will first sort by the first item, then if any ties occur sort on the second item, both in descending manner. We can make it descending by negating with the minus - sign.

But as suggested by @Heap Overflow, we don't need to do this because we can just pass reverse=True, and sorted() will naturally sort by the first item then the second in descending order. No need for a sorting key.

You can test this by running the following:

>>> sorted(lst, reverse=True)
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]
>>> sorted(lst, key=lambda x: (x[0], x[1]), reverse=True)
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]

Which both give the same results.

Upvotes: 1

Leo Arad
Leo Arad

Reputation: 4472

You can change the keyFunc to be like

def keyFunc(j):
    return j[0]*10+j[1]

or

ls = [[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]
sorted(ls, key=lambda x: x[0]*10+x[1], reverse=True)

That will sort both of the numbers as you described.

Upvotes: 1

Related Questions