Hello I am trying to figure out how to sort a nested list by multiple variables while some will not be sorted by 1,2,3 and instead by a predetermined list.
For Example:
List=[[XD,1],[XD,3],[XD,2],[X5,2],[X5,3],[XT,2]]
This would result in:
[[XD,1],[XD,2],[XD,3],[XT,2],[X5,2],[X5,3]]
The first element would be sorted by the sortbylist and the second element simply in numerical order.
SortByList={'XD': 'A', 'XT':'B', 'XQ': 'C','X5': 'D'}
I have currently been trying to use the code:
List.sort(key=SortByList.__getitem__ x: x[0])
List=sorted(List,key=itemgetter(1))
This however does not seem to work. Any hints?
One of the easiest ways to do this is:
Result=sorted(List, key=lambda x:(SortByList[x[0]],x[1]))
How about:
This uses a two-element compound key as explained in your question.