In SQL, we can specify desc/asc order for each sorting key, i.e. order by key1 desc, key2 asc. How can I acheive the same thing to sort a list of tuples in python?
Suppose I have a list like
[("a", "b", "e"), ("b", "a", "c"), ("b", "a", "d")] I want to use the second key in asc order and the third ky in desc order. So the result is
[("b", "a", "d"), ("b", "a", "c"), ("a", "b", "e")] Note, the elements can be any type that has comparison methods (i.e. __lt__, __gt__ etc)
sorted(sorted(l, key=lambda x:x[1]), key=lambda x:x[2], reverse=True). There may be a better solution than this!sortfor two times is redundant. There may be a better and generic solution than this ;-) !!!