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?

2
  • 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. Commented Feb 11, 2015 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])) Commented Feb 11, 2015 at 12:35

3 Answers 3

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)].

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.