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.

Community
  • 1
  • 1
  • 2
    A lambda expression does not need a `return` statement. – Willem Van Onsem Apr 30 '16 at 10:23
  • Possible duplicate of [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – AKS Apr 30 '16 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. –  Apr 30 '16 at 10:41

2 Answers2

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)]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

This also works and solves the question.

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