How to filter the list by selecting for unique combinations of characters in the elements (Python)?
<p>I have the the following pairs stored in the following list</p>

<pre><code> sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]]
</code></pre>

<p>Each pairwise comparison can have only two unique combinations of characters, if not then those pairwise comparisons are eliminated. eg,</p>

<pre><code>   In sample[1]
    C       C
    G       A
    C       T 
    G       C
</code></pre>

<p>Look a the corresponding elements in both sub-lists, CC, GA, CT, GC.</p>

<p>Here, there are more than two types of pairs (CC), (GA), (CT) and (GC). So this pairwise comparison cannot occur. </p>

<p>Every comparison can have only 2 combinations out of (AA, GG,CC,TT, AT,TA,AC,CA,AG,GA,GC,CG,GT,TG,CT,TC) ... basically all possible combinations of ACGT where order matters.</p>

<p>In the above example, more than 2 such combinations are found.</p>

<p>However, </p>

<pre><code>   In sample[0]
    C       A
    G       T
    C       A 
    G       T
</code></pre>

<p>There are only 2 unique combinations: CA and GT</p>

<p>Thus, the only pairs, that remain are:</p>

<pre><code>output = [[CGCG,ATAT],[ATAT,TATA]]
</code></pre>

<p>I would prefer if the code was in traditional for-loop format and not comprehensions</p>

<p>This is a small part of the question listed <a href="http://stackoverflow.com/questions/40066439/how-to-calculate-frequency-of-elements-for-pairwise-comparisons-of-lists-in-pyth/40073665?noredirect=1#comment67421103_40073665">here</a>. This portion of the question is re-asked, as the answer provided earlier provided incorrect output.</p>

<p>The core of this task is extracting the pairs from your sublists and counting the number of unique pairs.  Assuming your samples actually contain strings, you can use <code>zip(*sub_list)</code> to get the pairs.  Then you can use <code>set()</code> to remove duplicate entries.</p>

<pre><code>sample = [['CGCG','ATAT'],['CGCG','CATC'],['ATAT','CATC']]

def filter(sub_list, n_pairs):
    pairs = zip(*sub_list)
    return len(set(pairs)) == n_pairs
</code></pre>

<p>Then you can use a for loop or a list comprehension to apply this function to your main list.</p>

<pre><code>new_sample = [sub_list for sub_list in sample if filter(sub_list, 2)]
</code></pre>

<p>...or as a for loop...</p>

<pre><code>new_sample = []
for sub_list in sample:
    if filter(sub_list, 2):
        new_sample.append(sub_list)
</code></pre>

python list unique combinations