0

in this question was asked how to "Sorting a list in python from the second element on".

Is there any way to sort a list of lists in the same way? Example:

my_list = [
  ["1234", "aaa", "ccc", "bbb"],
  ["2332", "ggg", "bbb", "hhh"],
  ["4627", "ggg", "aaa", "hhh"],
  ["5332", "zzz", "vbb", "hhs"]
]

in

my_list = [
  ["1234", "aaa", "bbb", "ccc"],
  ["4627", "aaa", "ggg", "hhh"],
  ["2332", "bbb", "ggg", "hhh"],
  ["5332", "hhs", "vbb", "zzz"]
]

Thank you in advance

1 Answers1

1

I hope I understand your question right, you want to sort every item in list from second element, and then the whole list according second element:

my_list = [
  ["1234", "aaa", "ccc", "bbb"],
  ["2332", "ggg", "bbb", "hhh"],
  ["4627", "ggg", "aaa", "hhh"],
  ["5332", "zzz", "vbb", "hhs"]
]

my_list = sorted([[f, *sorted(v)] for f, *v in my_list], key=lambda k: k[1])

from pprint import pprint
pprint(my_list)

Prints:

[['1234', 'aaa', 'bbb', 'ccc'],
 ['4627', 'aaa', 'ggg', 'hhh'],
 ['2332', 'bbb', 'ggg', 'hhh'],
 ['5332', 'hhs', 'vbb', 'zzz']]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Thank you for the answer, even if the question was asked in an unclear way. I would like to specify that in my case I changed the code to `my_list = sorted([[f, *sorted(v)] for f, *v in my_list], key=lambda k: k[1:])` to order on all items and not just on the second. – Luca Squadrone Jun 04 '20 at 12:59