Sorting list B by list type A?

Let's say I have a list A with k elements and a list B with k elements. I want to sort list A, but also want to rearrange list B in the same way.

for example

A = [2,3,1,4]
B = [5,6,7,8]

      

after sorting A:

A = [1,2,3,4]
B = [7,5,6,8]

      

+3


source to share


2 answers


Here's one way:

>>> A = [2,3,1,4]
>>> B = [5,6,7,8]
>>> A, B = zip(*sorted(zip(A, B)))
>>> list(A)
[1, 2, 3, 4]
>>> list(B)
[7, 5, 6, 8]

      

In a nutshell:



  • zip A

    and B

    into the list of pairs;
  • sort pairs;
  • unzip back to A

    and B

    ;
  • convert tuples to lists.

If you like one-liners:

A, B = map(list, zip(*sorted(zip(A, B))))

      

+10


source


You can try something like this:

>>> A = [2,3,1,4]
>>> B = [5,6,7,8]
>>>
>>> AB = zip(A, B)
>>> AB.sort()
>>> A[:] = [t[0] for t in AB]
>>> B[:] = [t[1] for t in AB]
>>> A
[1, 2, 3, 4]
>>> B
[7, 5, 6, 8]

      



All we do here is "zipping" the list (ie in your example :) [(2, 5), (3, 6), (1, 7), (4, 8)]

and sorting that list by the first element of each tuple. Then, from this sorted list, we get the desired A

and B

.

+2


source







All Articles