Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in <code>zip</code> function:</p> <pre><code>&gt;&gt;&gt; list1 = [3,2,4,1, 1] &gt;&gt;&gt; list2 = ['three', 'two', 'four', 'one', 'one2'] &gt;&gt;&gt; list1, list2 = zip(*sorted(zip(list1, list2))) &gt;&gt;&gt; list1 (1, 1, 2, 3, 4) &gt;&gt;&gt; list2 ('one', 'one2', 'two', 'three', 'four') </code></pre> <p>These of course are no longer lists, but that's easily remedied, if it matters:</p> <pre><code>&gt;&gt;&gt; list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2)))) &gt;&gt;&gt; list1 [1, 1, 2, 3, 4] &gt;&gt;&gt; list2 ['one', 'one2', 'two', 'three', 'four'] </code></pre> <p>It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:</p> <pre><code>&gt;&gt;&gt; %timeit zip(*sorted(zip(list1, list2))) 100000 loops, best of 3: 3.3 us per loop &gt;&gt;&gt; %timeit tups = zip(list1, list2); tups.sort(); zip(*tups) 100000 loops, best of 3: 2.84 us per loop </code></pre> <p>On the other hand, for larger lists, the one-line version could be faster:</p> <pre><code>&gt;&gt;&gt; %timeit zip(*sorted(zip(list1, list2))) 100 loops, best of 3: 8.09 ms per loop &gt;&gt;&gt; %timeit tups = zip(list1, list2); tups.sort(); zip(*tups) 100 loops, best of 3: 8.51 ms per loop </code></pre> <p>As Quantum7 points out, <a href="https://stackoverflow.com/a/9764390/577088">JSF's suggestion</a> is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the <a href="https://hg.python.org/cpython/file/e4c32152b25b/Objects/listobject.c#l1863" rel="noreferrer">very same DSU idiom internally</a> for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the <code>zip</code> routines are!)</p> <p>I think the <code>zip</code>-based approach is more flexible and is a little more readable, so I prefer it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload