Note that there are some explanatory texts on larger screens.

plurals
  1. POInterleave different length lists, elimating duplicates and preserve order in Python
    primarykey
    data
    text
    <p>I have two lists, lets say:</p> <pre><code>keys1 = ['A', 'B', 'C', 'D', 'E', 'H', 'I'] keys2 = ['A', 'B', 'E', 'F', 'G', 'H', 'J', 'K'] </code></pre> <p>How do I create a merged list without duplicates that preserve the order of both lists, inserting the missing elements where they belong? Like so:</p> <pre><code>merged = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] </code></pre> <p>Note that the elements can be compared against equality but not ordered (they are complex strings). <strong>Update:</strong> The elements can't be ordered by comparing them, but they have a order based on their occurrence in the original lists.</p> <p><strong>Update:</strong> In case of contradiction (different order in both input lists), any output containing all elements is valid. Of course with bonus points if the solution shows 'common sense' in preserving most of the order.</p> <p><strong>Update:</strong> Again (as some comments still argue about it), the lists normally don't contradict each other in terms of the order of the common elements. In case they do, the algorithm needs to handle that error gracefully.</p> <p>I started with a version that iterates over the lists with .next() to advance just the list containing the unmatched elements, but .next() just doesn't know when to stop.</p> <pre><code>merged = [] L = iter(keys1) H = iter(keys2) l = L.next() h = H.next() for i in range(max(len(keys1, keys2))): if l == h: if l not in merged: merged.append(l) l = L.next() h = H.next() elif l not in keys2: if l not in merged: merged.append(l) l = L.next() elif h not in keys1: if h not in merged: merged.append(h) h = H.next() else: # just in case the input is badly ordered if l not in merged: merged.append(l) l = L.next() if h not in merged: merged.append(h) h = H.next() print merged </code></pre> <p>This obviously doesn't work, as .next() will cause an exception for the shortest list. Now I could update my code to catch that exception every time I call .next(). But the code already is quite un-pythonic and this would clearly burst the bubble.</p> <p>Does anyone have a better idea of how to iterate over those lists to combine the elements?</p> <p>Bonus points if I can do it for three lists in one go.</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.
 

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