0

I have two lists ns and ts. I would like to sort ns and then, based on the way it was sorted, move around ts so that it matches ns accordingly. Something like this would be the input and output:

ns = (0 4 2 5 1)
ts = (1 2 3 4 5)

ns = (0 1 2 4 5)
ts = (1 5 3 2 4) 

I know that I can sort each of these via ns.sort() and ts.sort(), but this will only help to sort ns.

drjrm3
  • 4,474
  • 10
  • 53
  • 91

2 Answers2

1

You could sort the two lists zipped together:

In [5]: sorted(zip(ns, ts))
Out[5]: [(0, 1), (1, 5), (2, 3), (4, 2), (5, 4)]

And then grab the second element in the tuples:

In [6]: [pair[1] for pair in sorted(zip(ns, ts))]
Out[6]: [1, 5, 3, 2, 4]

Or less readable:

zip(*sorted(zip(ns, ts)))[1]
Blender
  • 289,723
  • 53
  • 439
  • 496
0

Zip, sort, unzip, unpack:

ns = (0, 4, 2, 5, 1)
ts = (1, 2, 3, 4, 5)
ns, ts = zip(*sorted(zip(ns, ts)))
Shashank
  • 13,713
  • 5
  • 37
  • 63