JMAz
JMAz

Reputation: 97

How to sort a list by my order for several times?

I have just started coding with python recently. I am trying to sort my list as a dictionary which I've made. this is the dictionary:

X={'Si':6,'La':5,'Sol':4,'Fa':3,'Mi':2,'Re':1,'Do':0}

And I have a list like this:

A=[['Do', 'Do'], ['Re', 'Do'], ['Do', 'Mi'], ['Si', 'Do'], ['Fa', 'Fa'], ['Mi', 'Fa'], ['Sol', 'Si']]

I intend to sort this list into:

[['Do', 'Do'], ['Do', 'Mi'], ['Re', 'Do'], ['Mi', 'Fa'], ['Fa', 'Fa'], ['Sol', 'Si'], ['Si', 'Do']]

I mean sorting this list by sorting first element then the second element and third and ...

I have tried to fulfill this by using this code:

A.sort(key=lambda val: X[val[0]])

Therefore, I could sort the list by the first item, but for the second or third(if the inner lists contain more items) I cannot sort them. I'm not a Groovy coder so thanks for the help in advance.

Upvotes: 3

Views: 58

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Sorting by multiple "fields":

X = {'Si':6,'La':5,'Sol':4,'Fa':3,'Mi':2,'Re':1,'Do':0}
A = [['Do', 'Do'], ['Re', 'Do'], ['Do', 'Mi'], ['Si', 'Do'], ['Fa', 'Fa'], ['Mi', 'Fa'], ['Sol', 'Si']]
result = sorted(A, key=lambda lst: tuple(X[i] for i in lst))

print(result)

The output:

[['Do', 'Do'], ['Do', 'Mi'], ['Re', 'Do'], ['Mi', 'Fa'], ['Fa', 'Fa'], ['Sol', 'Si'], ['Si', 'Do']]

Upvotes: 2

Related Questions