Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would do something like this:</p> <pre><code>from collections import defaultdict a = [1, 2, 3] b = [1, 2, 3, 1, 2, 3] # Build up the count of occurrences in b d = defaultdict(int) for bb in b: d[bb] += 1 # Remove one for each occurrence in a for aa in a: d[aa] -= 1 # Create a list for all elements that still have a count of one or more result = [] for k, v in d.iteritems(): if v &gt; 0: result += [k] * v </code></pre> <p>Or, if you are willing to be slightly more obscure:</p> <pre><code>from operator import iadd result = reduce(iadd, [[k] * v for k, v in d.iteritems() if v &gt; 0], []) </code></pre> <p>defaultdict generates a count of the occurrences of each key. Once it has been built up from <code>b</code>, it is decremented for each occurrence of a key in <code>a</code>. Then we print out the elements that are still left over, allowing them to occur multiple times.</p> <p>defaultdict works with python 2.6 and up. If you are using a later python (2.7 and up, I believe), you can look into <a href="http://docs.python.org/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>.</p> <hr> <p>Later: you can also generalize this and create subtractions of counter-style defaultdicts:</p> <pre><code>from collections import defaultdict from operator import iadd a = [1, 2, 3, 4, 5, 6] b = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] def build_dd(lst): d = defaultdict(int) for item in lst: d[item] += 1 return d def subtract_dd(left, right): return {k: left[k] - v for k, v in right.iteritems()} db = build_dd(b) da = build_dd(a) result = reduce(iadd, [[k] * v for k, v in subtract_dd(db, da).iteritems() if v &gt; 0], []) print result </code></pre> <p>But the <code>reduce</code> expression is pretty obscure now.</p> <hr> <p>Later still: in python 2.7 and later, using <code>collections.Counter</code>, it looks like this:</p> <pre><code>from collections import Counter base = [1, 2, 3] missing = [4, 5, 6] extra = [7, 8, 9] a = base + missing b = base * 4 + extra result = Counter(b) - Counter(a) print result assert result == dict([(k, 3) for k in base] + [(k, 1) for k in extra]) </code></pre>
 

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