0

I have a 2D List -

[('John', 7), ('Max', 10), ('Sarah', 10), ('Tara', 7)]

which I would like to sort by number descending (highest first) and then name (alphabetical).

I have used this code -

highestscore = sorted(highestscore, key = lambda x: (x[1],x[0]), reverse=True)

but I get the result

[('Sarah', 10), ('Max', 10), ('Tara', 7), ('John', 7)]

Any ideas?

  • 1
    not reversing the list? I mean the output looks correct to me, that Sarah has the highest score a long with Max and then Tara and John. – Thomas Lindvall Feb 11 '15 at 12:25
  • Instead of reassigning the result of `sorted()` to the same variable, you can just sort in place: `highestscore.sort(key=lambda x: (-x[1], x[0]))` – mhawke Feb 11 '15 at 12:35

3 Answers3

3

You need to mix descending order (score) with ascending (name). You may just use -x[1] instead of reverse=True:

highestscore = sorted(highestscore, key = 
    lambda x: (int(-x[1]), x[0].lower()))

I also added lower() to make alphabetical ordering case insensitive. The result is [('Max', 10), ('Sarah', 10), ('John', 7), ('Tara', 7)].

Tupteq
  • 2,986
  • 1
  • 21
  • 30
0

How about try this:

a = [('John', 7), ('Max', 10), ('Sarah', 10), ('Tara', 7)]
a.sort(key=lambda x: x[0])
a.sort(key=lambda x: x[1], reverse=True)

The result is:

[('Max', 10), ('Sarah', 10), ('John', 7), ('Tara', 7)]

Refererence: How can I sort tuples by reverse, yet breaking ties non-reverse? (Python)

Community
  • 1
  • 1
Wes
  • 1,720
  • 3
  • 15
  • 26
0

You sorting is all right... You need to transform your elements with a map afterwards.

highestscore = sorted(highestscore, key = lambda x: (x[1],x[0]), reverse=True)

scores = [ ( x[ 1 ], x[ 0 ] ) for x in highestscore ]

The result will be

[(10, 'Max'), (10, 'Sarah'), (7, 'John'), (7, 'Tara')]
sarveshseri
  • 13,738
  • 28
  • 47