2

Initially, a list of tuples is sorted by their second value and their third value.

tlist = [('a', 1, 14), ('a', 1, 16), ('b', 1, 22), 
        ('a', 2, 1), ('c', 2, 9), ('d', 2, 11), ('d', 2, 12)]

Trying to sort this list of tuples by their second value, reverse by their third value; that is, want the output of the list to be sorted like so:

tlist= [('b', 1, 22), ('a', 1, 16), ('a', 1, 14), 
        ('d', 2, 12), ('d', 2, 11), ('c', 2, 9), ('a', 2, 1)]

This is what I have tried so far as seen in this answer:

tlist = sorted(tlist, key=lambda t: return (t[0], t[1], -t[2]))

but it does not work; gives a return outside of function error.

Any ides of how to get the desired output?

EDIT

This question provides very good resources and perhaps all someone would need to go ahead and tackle my specific question. However, given my low level of experience and my specific instance of sorting with different sorting criteria (as described on the description above), I think this is no duplicate.

3
  • 2
    A lambda expression does not need a return statement. Commented Apr 30, 2016 at 10:23
  • Possible duplicate of How to sort (list/tuple) of lists/tuples? Commented Apr 30, 2016 at 10:33
  • @AKS You have a point for my question having similarity with the question you note; I edited my question to point out why I feel it is not a duplicate due to different sorting criteria. Commented Apr 30, 2016 at 10:41

2 Answers 2

5

A lambda expression does not use a return statement. You should thus drop the return keyword.

You also seem to sort first on the first element of the tuples. In order to only take the second element and use descending order of the third element as a tie breaker, you should rewrite the lambda to:

lambda t: (t[1],-t[2])

Or putting it all together:

tlist = sorted(tlist, key=lambda t: (t[1],-t[2]))

Running this in python3 generates:

>>> tlist= [('b', 1, 22), ('a', 1, 16), ('a', 1, 14), 
...         ('d', 2, 12), ('d', 2, 11), ('c', 2, 9), ('a', 2, 1)]
>>> tlist = sorted(tlist, key=lambda t: (t[1],-t[2]))
>>> list(tlist)
[('b', 1, 22), ('a', 1, 16), ('a', 1, 14), ('d', 2, 12), ('d', 2, 11), ('c', 2, 9), ('a', 2, 1)]
Sign up to request clarification or add additional context in comments.

2 Comments

this is duplicated, why answering?
@ColonelBeauvel: The second "error" is not a duplicate I think, if you only drop the return statement, it will take the first element of the tuple as primary sorting criterium.
2

This also works and solves the question.

>>> sorted(tlist, key=lambda t : (-t[1], t[2]), reverse=True)

Comments

Your Answer

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