3
l = [0, 1, 3, 2]

l2 = ['foo', 3, 'bar', 10]

If I say sorted(l), I will get [0, 1, 2, 3]. It will swap the last two elements.

How can I apply the same row swaps to l2? I.e., I want l2 to be ['foo', 3, 10, 'bar'].

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Ogen
  • 6,499
  • 7
  • 58
  • 124

2 Answers2

6

You can use zip, unpack tuple and a list comprehension to achieve the results:

[y for x, y in sorted(zip(l, l2))]
zw324
  • 26,764
  • 16
  • 85
  • 118
  • so when you say `sorted` on a list of tuples it will sort the list based on the first values of each tuple? – Ogen May 24 '15 at 04:24
  • 1
    Tuples are compared as a sequence, which means compare first element first, if equal, compare second, etc. See http://stackoverflow.com/questions/5292303/python-tuple-comparison. – zw324 May 24 '15 at 04:25
  • 2
    Note that if two elements of `l` are equal, this will compare the elements of `l2` to determine the order. This may be undesirable, especially on Python 3, where trying to compare semantically unordered types will produce an exception. If this is a problem, you can use `[z for x, y, z in sorted(zip(l, range(len(l)), l2)]` to avoid comparing elements of `l2`. – user2357112 May 24 '15 at 04:31
  • 3
    Or, more simply, you can just use a `key` function as the tie breaker: `[y for x, y in sorted(zip(l, l2), key=itemgetter(0))]`. – abarnert May 24 '15 at 04:40
4

TL;DR

>>> l, l2 = zip(*sorted(zip(l, l2)))
>>> list(l)
[0, 1, 2, 3]
>>> list(l2)
['foo', 3, 10, 'bar']

Explanation

  1. zip both the lists together

    >>> list(zip(l, l2))
    [(0, 'foo'), (1, 3), (2, 10), (3, 'bar')]
    
  2. then sort them, (since we get tuples from zip, the first elements of tuples will be compared first and only if they are same, the second element will be compared. So the sorting effectively happens with the values of l)

    >>> sorted(zip(l, l2))
    [(0, 'foo'), (1, 3), (2, 10), (3, 'bar')]
    
  3. and then unzip them,

    >>> list(zip(*sorted(zip(l, l2))))
    [(0, 1, 2, 3), ('foo', 3, 10, 'bar')]
    

    you can actually unzip over l and l2, like this

    >>> l, l2 = zip(*sorted(zip(l, l2)))
    >>> l, l2
    ((0, 1, 2, 3), ('foo', 3, 10, 'bar'))
    >>> list(l)
    [0, 1, 2, 3]
    >>> list(l2)
    ['foo', 3, 10, 'bar']
    

Alternate approach

You can actually sort the values along with the current index and then you can reconstruct the values like this

>>> l = [0, 1, 3, 2]
>>> l2 = ['foo', 3, 'bar', 10]
>>> l_s = sorted((value, idx) for idx, value in enumerate(l))
>>> l_s
[(0, 0), (1, 1), (2, 3), (3, 2)]
>>> l = [value for value, idx in l_s]
>>> l
[0, 1, 2, 3]
>>> l2 = [l2[idx] for value, idx in l_s]
>>> l2
['foo', 3, 10, 'bar']
thefourtheye
  • 233,700
  • 52
  • 457
  • 497