Matching the structure of a list?
<p>For example:</p>

<pre><code>A=[1,[2,3],[4,[5,6]],7]
B=[2,3,4,5,6,7,8]
</code></pre>

<p>How can I get <code>[2,[3,4],[5,[6,7]],8]</code>?</p>

<p>You could use a pretty simple recursive function:</p>

<pre><code>def match(struct, source):
    try:
        return [match(i, source) for i in struct]
    except TypeError:
        return next(source)

A=[1,[2,3],[4,[5,6]],7]
B=[2,3,4,5,6,7,8]
match(A, iter(B))
# [2, [3, 4], [5, [6, 7]], 8]
</code></pre>

<p>Here is a version of the function that might be a little easier for some people to understand:</p>

<pre><code>def match(struct, source, index=0):
    if isinstance(struct, list):
        r = []
        for item in struct:
            next, index = match(item, source, index)
            r.append(next)
        return r, index
    else:
        return source[index], index + 1

A=[1,[2,3],[4,[5,6]],7]
B=[2,3,4,5,6,7,8]
match(A, B)
</code></pre>

<p>The basic idea is to loop over the input structure depth first, and consume values from source accordingly. When we hit a number, we can simply take one number from source. If we hit a list we need to apply this algorithm to that list. Along the way need to keep track of how many items we've consumed.</p>

<p>The first version of the algorithm does all this, but in a slightly different way. <code>iter(B)</code> creates an iterator that tracks how many items from b have been consumed and provided the next item when i call <code>next(source)</code> so I don't have to track index explicitly. The try/except checks to see if I can loop over <code>struct</code>. If I can, a list is returned, if I cannot the expect block gets executed and <code>next(source)</code> is returned.</p>

python list