擅长:python、mysql、java
<p>使用<a href="https://docs.python.org/2.7/library/collections.html#collections.Counter" rel="nofollow">Counter</a>可以使它更容易一些,并且避免使用字典(我喜欢dicts,但是在本例中,<code>Counter</code>确实有意义)。在</p>
<pre><code>from collections import Counter
acids = "" # dunno if this is the right terminology
with open(filename, 'r') as ecoli_file:
for line in ecoli_file:
if line.startswith('>'):
continue
# from what I saw in the FASTA files, the character-check is
# not necessary anymore...
acids += line.strip() # stripping newline and possible whitespaces
counter = Counter(acids) # and all the magic is done.
total = float(sum(counter.values()))
for k, v in counter.items():
print "{}: {} ({:.1%})".format(k, v, v / total)
</code></pre>
<p>由于<code>Counter</code>接受ITerable,因此应该可以使用生成器来完成:</p>
^{pr2}$