Sorting list B by list type A?
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
andB
into the list of pairs; - sort pairs;
- unzip back to
A
andB
; - convert tuples to lists.
If you like one-liners:
A, B = map(list, zip(*sorted(zip(A, B))))
+10
source to share
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 to share