I have a list in python like -
[['C'], ['B'], ['A'], ['C', 'B'], ['B', 'A'], ['A', 'C']]
I want to sort it like follows -
[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C']]
List objects have a sort () method that will sort the list alphanumerically, ascending, by default: To sort descending, use the keyword argument reverse = True: You can also customize your own function by using the keyword argument key = function. The function will return a number that will be used to sort the list (the lowest number first):
We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x [1]. Then, it will sort the first element, x [0] (highest priority). no, this sorting rule need to take precedence then second.
How to sort the list of lists by the sum of elements If we want to sort the list according to the sum of elements of the inner list, we can use the key as ‘sum’. 5. Sorting the list of lists in descending order Let us now sort the list in descending order. We can use the reverse parameter of the sort method.
The sort () method sorts the list ascending by default. You can also make a function to decide the sorting criteria (s). Optional. reverse=True will sort the list descending. Default is reverse=False Optional. A function to specify the sorting criteria (s) Sort the list by the length of the values and reversed:
First sort the individual items in the lists and then sort the sorted lists based on the length and then the actual elements itself, like this
>>> data = [['C'], ['B'], ['A'], ['C', 'B'], ['B', 'A'], ['A', 'C']]
>>> sorted((sorted(item) for item in data), key=lambda x: (len(x), x))
[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C']]
This works because, list of strings will be sorted lexicographically, by default. In your case, when the internal lists are sorted, the outer lists are first sorted based on the length of the list and if they are the same then the actual elements of the string itself will be used for the comparison.
This can be understood step-by-step. The first individual elements sorting results in this
>>> [sorted(item) for item in data]
[['C'], ['B'], ['A'], ['B', 'C'], ['A', 'B'], ['A', 'C']]
Now, we need to sort this based on the length in ascending order first, and then the elements also should be sorted. So, we pass a custom function to the outer sorting function, lambda x: (len(x), x)
.
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