counting occurrence of elements in each sequence of the list in python
<p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p>

<p>small example:</p>

<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']
</code></pre>

<p>do you guys know how to do that?</p>

<p>You can simply use a <em>list comprehension</em>, get the count of <code>D</code> in each sequence and divide by the length of the sequence:</p>

<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']

result = [x.count('D')/len(x) for x in l]
print(result)
# [0.07692307692307693, 0.125, 0.125, 0.21428571428571427, 0.17647058823529413]
</code></pre>

<p>To handle zero length sequences and avoid <code>ZeroDivisionError</code>, you may use a <em>ternary operator</em>:</p>

<pre><code>result = [(x.count('D')/len(x) if x else 0) for x in l]
</code></pre>

python