How do I sort a list in python by comparing it to a single list?

so let's say I have a list:

A = [cat, dog, mouse, horse, bird, rabbit]

      

which will be used as a list of links and another list:

B = [dog, rabbit, horse, bird, cat, dog]

      

which has the same elements as the list of links, but in a different order. I want to sort list B in the same order as list A, so I tried:

for indexA in range(0, len(A)):
    for indexB in range(0, len(B)):
        if A[indexA] == B[indexB]:
            B[indexA], B[indexB] = B[indexB], B[indexA]

      

but it doesn't work ... What is the best way to do this?

+1


source to share


2 answers


You can use sort

or sorted

with key

to use the A.index

current word.



>>> sorted(B, key = A.index)
['cat', 'dog', 'dog', 'horse', 'bird', 'rabbit']

      

+4


source


Not that algorithmic complexity matters for such small lists, but you can avoid Omega (n * m):

ranks = dict((value, idx) for idx, value in enumerate(A))
B.sort(key = ranks.get)

      

A more concise way to write the first line:



ranks = dict(map(reversed, enumerate(A)))

      

... but I cannot decide if this is too much for public consumption!

+3


source







All Articles