Royston Teo
Royston Teo

Reputation: 121

Sort list based on how another list is sorted

I have 2 list like this:

    A = [10, 29, 30, 49, 21, 3, 5, 6]
    B = [y, z, t, e, q, f, h, d]

I want list B to sort the same way as list A after sort() function, example of output:

    A.sort()
    print(A) 
    >>>[3, 5, 6, 10, 21, 29, 30, 49]
    print(B)
    >>>[f, h, d, y, q, z, t, e]

Upvotes: 3

Views: 74

Answers (1)

Nick
Nick

Reputation: 28006

Zip the two lists together. Sort on the first item of each pair, and then unzip.

Upvotes: 6

Related Questions