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]
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]
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:
A
and B
into a list of pairs;A
and B
;If you like one-liners:
A, B = map(list, zip(*sorted(zip(A, B))))
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
.