Python - separate duplicate objects into different list
<p>So let say I have this class:</p>

<pre><code>class Spam(object):
    def __init__(self, a):
        self.a = a
</code></pre>

<p>And now I have these objects:</p>

<pre><code>s1 = Spam((1, 1, 1, 4))

s2 = Spam((1, 2, 1, 4))

s3 = Spam((1, 2, 1, 4))

s4 = Spam((2, 2, 1, 4))

s5 = Spam((2, 1, 1, 8))

s6 = Spam((2, 1, 1, 8))

objects = [s1, s2, s3, s4, s5, s6]
</code></pre>

<p>so after running some kind of method, I need to have two lists that have objects that had same <code>a</code> attribute value in one list and the other objects that had unique <code>a</code> attribute.</p>

<p>Like this:</p>

<pre><code>dups = [s2, s3, s5, s6]
normal = [s1, s4]
</code></pre>

<p>So it is something like getting duplicates, but in addition it should also add even first occurrence of object that shares same <code>a</code> attribute value.</p>

<p>I have written this method and it seems to be working, but it is quite ugly in my opinion (and probably not very optimal). </p>

<pre><code>def eggs(objects):
    vals = []
    dups = []
    normal = []
    for obj in objects:
        if obj.a in vals:
            dups.append(obj)
        else:
            normal.append(obj)
            vals.append(obj.a)
    dups_vals = [o.a for o in dups]
    # separate again
    new_normal = []
    for n in normal:
        if n.a in dups_vals:
            dups.append(n)
        else:
            new_normal.append(n)
    return dups, new_normal
</code></pre>

<p>Can anyone write more appropriate pythonic approach for such problem?</p>

<p>Using <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>, these are the keys that are common to more than one:</p>

<pre><code>import collections

common = [k for (k, v) in collections.Counter([o.a for o in objects]).items() if v &gt; 1]
</code></pre>

<p>Your two lists, now are</p>

<pre><code>[o for o in objects if o.a in common], [o for o in objects if o.a not in common]
</code></pre>

python duplicates unique