I was wondering what would be a Pythonic way of sorting a list of tuples by two keys whereby sorting with one (and only one) key would be in a reverse order and sorting with the the other would be case insensitive. More specifically, I have a list containing tuples like:
myList = [(ele1A, ele2A),(ele1B, ele2B),(ele1C, ele2C)]
I can use the following code to sort it with two keys:
sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]))
To sort in reverse order I can use
sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]), reverse = True)
But this would sort in a reverse order with two keys.
In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method. reverse() method reverses the sequence of the list permanently.
@moose, @Amyth, to reverse to only one attribute, you can sort twice: first by the secondary s = sorted(s, key = operator. itemgetter(2)) then by the primary s = sorted(s, key = operator.
To sort a Python list by two fields, we can use the sorted function. to call sorted to return the list items sorted by calling it with the key argument set to a lamnda function that has a tuple of values to sort by. We sort x[1] in descending order since we have a minus sign before the value.
Python sort list of tuples by first and second element. To sort the first tuple element we can use an index() method like list[0]. Similar to the second element we can use the list[1] index. By using the sort method we need to sort the lists in place and order.
Two keys will be used when we need to sort a list with two constraints one in ascending order and other in descending in the same list or any
In your example sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]))
can sort entire list only in one order
you can try these and check whats happening
sortedList = sorted(myList, key = lambda y: (y[0].lower(), -y[1])) sortedList = sorted(myList, key = lambda y: (-y[0].lower(), y[1])) sortedList = sorted(myList, key = lambda y: (-y[0].lower(), -y[1]))
hope you will understand after this ;)
You could create a reversor class and use it to decorate the key in question. This class could be used to reverse any field that is comparable.
class reversor: def __init__(self, obj): self.obj = obj def __eq__(self, other): return other.obj == self.obj def __lt__(self, other): return other.obj < self.obj
Use it like so:
sortedList = sorted(myList, key=lambda(y): (y[0].lower(), reversor(y[1])))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With