Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A true <code>itertools</code>-based solution that works on an iterable:</p> <pre><code>&gt;&gt;&gt; part_iter = iter(part_list) &gt;&gt;&gt; part_in, part_out = itertools.tee(part_iter) &gt;&gt;&gt; in_main = (p for p in part_in if p in main_list) &gt;&gt;&gt; out_main = (p for p in part_out if p not in main_list) </code></pre> <p>Making lists out of these defeats the point of using iterators, but here is the result:</p> <pre><code>&gt;&gt;&gt; list(in_main) [4, 1] &gt;&gt;&gt; list(out_main) [5, 2, 7] </code></pre> <p>This has the advantage of lazily generating <code>in_main</code> and <code>out_main</code> from another lazily generated sequence. The only catch is that if you iterate through one before the other, <code>tee</code> has to cache a bunch of data until it's used by the other iterator. So this is really only useful if you iterate through them both at roughly the same time. Otherwise you might as well use auxiliary storage yourself.</p> <p>There's also an interesting ternary operator-based solution. (You could squish this into a list comprehension, but that would be wrong.) I changed main_list into a set for O(1) lookup. </p> <pre><code>&gt;&gt;&gt; main_set = set(main_list) &gt;&gt;&gt; in_main = [] &gt;&gt;&gt; out_main = [] &gt;&gt;&gt; for p in part_list: ... (in_main if p in main_set else out_main).append(p) ... &gt;&gt;&gt; in_main [4, 1] &gt;&gt;&gt; out_main [5, 2, 7] </code></pre> <p>There's also a fun <code>collections.defaultdict</code> approach:</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; in_out = collections.defaultdict(list) &gt;&gt;&gt; for p in part_list: ... in_out[p in main_list].append(p) ... &gt;&gt;&gt; in_out defaultdict(&lt;type 'list'&gt;, {False: [5, 2, 7], True: [4, 1]}) </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.
 

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