Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a 2D list alphabetically?

I have a 2D list such as this:

lst = [['c', 'd', 'b'], ['d', 'c', 'a'], ['b', 'a', 'c']]

I would first like to sort each list within the list alphabetically like this:

lst = [['b', 'c', 'd'], ['a', 'c', 'd'], ['a', 'b', 'c']]

And finally, I would like to sort the whole list alphabetically which takes into account each element in a sublist:

lst = [['a', 'b', 'c'], ['a', 'c', 'd'], ['b', 'c', 'd']]

What would be the fastest way to achieve this? Thank you.

like image 961
Arjun Vasudevan Avatar asked Feb 05 '23 03:02

Arjun Vasudevan


1 Answers

The fastest way in general should be just as you described it:

for sublist in lst:
    sublist.sort()

lst.sort()

Alternatively, if you want to do it out of place:

new_lst = [sorted(sublist) for sublist in lst]
new_lst.sort()
like image 177
mgilson Avatar answered Feb 07 '23 15:02

mgilson