擅长:python、mysql、java
<p>这个解决方案可以用不同的方式来实现,而且作为一个基于循环的解决方案,它非常简单,留给您作为练习</p>
<p>为了让您体验一下Python电池的强大功能,我提出了一个使用groupby的解决方案</p>
<pre><code>>>> ''.join("{}{}".format(k, sum(1 for e in v))
for k,v in groupby("AAABBBBCDDDDDDDDDDEEDDDD"))
'A3B4C1D10E2D4'
</code></pre>
<p>此解决方案的显著特点</p>
<ol>
<li><a href="http://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby</a>将类似的连续数据分组为键-值对,其中key是重复元素,value是重复组</li>
<li>由于组是生成器,<a href="http://docs.python.org/2/library/functions.html#len" rel="nofollow">len</a>在这里可能不起作用,但是计算任何非序列iterable的长度的一种可能的方法是使用<a href="http://docs.python.org/2/library/functions.html#sum" rel="nofollow">sum</a></li>
<li><a href="http://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow">str.join</a>连接iterable以生成带有任何分隔符的字符串,在本例中它是一个空字符串</li>
</ol>