擅长:python、mysql、java
<p>使用<a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow">^{<cd1>}</a>可以很快完成此操作。在</p>
<pre><code>from collections import Counter
s = "CTAACAAC"
def chunk_string(s, n):
return [s[i:i+n] for i in range(len(s)-n+1)]
counter = Counter(chunk_string(s, 3))
# Counter({'AAC': 2, 'ACA': 1, 'CAA': 1, 'CTA': 1, 'TAA': 1})
</code></pre>
<hr/>
<p><strong>编辑:</strong>详细说明<code>chunk_string</code>:</p>
<p>它以字符串<code>s</code>和块大小<code>n</code>作为参数。每个<code>s[i:i+n]</code>是一个长度为<code>n</code>个字符的字符串片段。循环迭代有效的索引,其中字符串可以被切片(<code>0</code>到<code>len(s)-n</code>)。然后将所有这些片段分组到一个列表理解中。等效方法为:</p>
^{pr2}$