3

Let's say I have some list A with k elements, and list B with k elements as well. I want to sort list A, but I also want to permute 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]
MyNameIsKhan
  • 2,594
  • 8
  • 36
  • 56
  • 2
    possible duplicate of [Sorting list based on values from another list?](http://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list) – buydadip Jan 07 '15 at 20:16
  • 1
    @Bolboa: Not quite a dupe since this question is asking to preserve both `A` and `B`. The other question doesn't address that. – NPE Jan 07 '15 at 20:19
  • @NPE I see, perhaps your right. – buydadip Jan 07 '15 at 20:21

2 Answers2

11

Here is 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 a list of pairs;
  • sort the pairs;
  • unzip back into A and B;
  • convert tuples to lists.

If you like one-liners:

A, B = map(list, zip(*sorted(zip(A, B))))
Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    @MyNameIsKhan: `zip(*)` undoes the first `zip`: http://stackoverflow.com/questions/13635032/what-is-the-inverse-function-of-zip-in-python – NPE Jan 07 '15 at 20:17
2

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're doing here is "zipping" the list (i.e. 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 retrieve the desired A and B.

arshajii
  • 127,459
  • 24
  • 238
  • 287