How to return the value of a counter in Python when comparing non-identical elements?
<p>I have the following list:</p>

<pre><code>x = [['A', 'A', 'A', 'A'], ['C', 'T', 'C', 'C'], ['G', 'T', 'C', 'C'], ['T', 'T', 'C', 'C'], ['A', 'T', 'C']]
</code></pre>

<p>I need to compare each element in sub_list to the other and note number of changes</p>

<pre><code>x[0] --&gt; # No change 
x[1] --&gt; # 1 change (Only one conversion from C to T (T to C conversion = C to T conversion))
x[2] --&gt; # 3 changes(G to T, T to C, G to C (T to C conversion = C to T conversion))
</code></pre>

<p>....
So, final count for Changes should be [0,1,3,2,3]</p>

<p>If I understand well...</p>

<pre><code>from collections import Counter
from itertools import combinations

x = [['A', 'A', 'A', 'A'],
     ['C', 'T', 'C', 'C'],
     ['G', 'T', 'C', 'C'],
     ['T', 'T', 'C', 'C'],
     ['A', 'T', 'C', 'Z']]


def divide_and_square(number, divisor):
    return (1. * number / divisor) ** 2


# part1
counters = [Counter(sub_list) for sub_list in x]
atgc_counts = [sum(val for key, val in counter.items()
                   if key.upper() in "ATGC")
               for counter in counters]
print(atgc_counts)

# part 2
conversions = []
for sl in x:
    sub_list = [base for base in sl if base.upper() in "ATGC"]
    conversions.append(len(list(combinations(set(sub_list), 2))))
print(conversions)

# bonus
squared_factor_sums = []
for counter in counters:
    total = sum(counter.itervalues())
    squared_factor_sums.append(sum([divide_and_square(val, total)
                                    for val in counter.values()]))
print(squared_factor_sums)
</code></pre>

<p>prints:</p>

<pre><code>[4, 4, 4, 4, 3]
[0, 1, 3, 1, 3]
[1.0, 0.625, 0.375, 0.5, 0.25]
</code></pre>

<ul>
<li>first the character other that ATGC are removed.</li>
<li>then the duplications are avoided by casting the sub_list into a set</li>
<li><a href="https://docs.python.org/2/library/itertools.html?highlight=itertools.combinations#itertools.combinations" rel="nofollow">itertools.combinations</a> is used to get all the unique combinations of the elements in the set</li>
<li>combinations are finally counted</li>
</ul>

python list compare counter