Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a solution using <a href="http://docs.python.org/3.2/library/itertools.html#itertools.zip_longest" rel="nofollow"><code>itertools.zip_longest</code></a> and a <a href="http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>&gt;&gt;&gt; from itertools import zip_longest &gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = ["hi", "bye", True, False, 33] &gt;&gt;&gt; [y for x in zip_longest(a, b) for y in x] [1, 'hi', 2, 'bye', 3, True, None, False, None, 33] &gt;&gt;&gt; [y for x in zip_longest(a, b) for y in x if y is not None] [1, 'hi', 2, 'bye', 3, True, False, 33] &gt;&gt;&gt; </code></pre> <hr> <p><strong>Edit:</strong></p> <p>If you don't want to use <code>itertools</code>, I guess you could do:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = ["hi", "bye", True, False, 33] &gt;&gt;&gt; items = sorted((a,b), key=len) &gt;&gt;&gt; out = [] &gt;&gt;&gt; for x,y in enumerate(items[1]): ... out.append(y) ... try: ... out.append(items[0][x]) ... except IndexError: ... out.extend(items[1][x+1:]) ... break ... &gt;&gt;&gt; out ['hi', 1, 'bye', 2, True, 3, False, 33] &gt;&gt;&gt; </code></pre> <p>But I must say this method isn't as efficient as my first solution.</p> <hr> <p><strong>Edit 2:</strong></p> <p>Changing <code>enumerate</code> to <code>zip</code> reduces the efficiency again. However, if you <em>must</em>, then you can do this:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = ["hi", "bye", True, False, 33] &gt;&gt;&gt; out = [] &gt;&gt;&gt; items = sorted((a,b), key=len) &gt;&gt;&gt; for x,y in zip(range(len(items[1])), items[1]): ... out.append(y) ... try: ... out.append(items[0][x]) ... except IndexError: ... out.extend(items[1][x+1:]) ... break ... &gt;&gt;&gt; out ['hi', 1, 'bye', 2, True, 3, False, 33] &gt;&gt;&gt; </code></pre>
    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. 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.
 

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