Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is an adapted version of the roundrobin recipe from the <a href="http://docs.python.org/2/library/itertools.html#recipes" rel="nofollow">itertools documentation</a> that should do what you want:</p> <pre><code>from itertools import cycle, islice def merge(a, b, pos): "merge('ABCDEF', [1,2,3], 3) --&gt; A B 1 C D 2 E F 3" iterables = [iter(a)]*(pos-1) + [iter(b)] pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; list(merge(xrange(1, 9), 'abc', 3)) # note that this works for any iterable! [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8] </code></pre> <p>Or here is how you could use <code>roundrobin()</code> as it is without any modifications:</p> <pre><code>&gt;&gt;&gt; x = [1,2,3,4,5,6,7,8] &gt;&gt;&gt; y = ['a','b','c'] &gt;&gt;&gt; list(roundrobin(*([iter(x)]*2 + [y]))) [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8] </code></pre> <p>Or an equivalent but slightly more readable version:</p> <pre><code>&gt;&gt;&gt; xiter = iter(x) &gt;&gt;&gt; list(roundrobin(xiter, xiter, y)) [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8] </code></pre> <p>Note that both of these methods work with any iterable, not just sequences.</p> <p>Here is the original <code>roundrobin()</code> implementation:</p> <pre><code>from itertools import cycle, islice def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --&gt; A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) </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. 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.
    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