擅长:python、mysql、java
<p>如果您不担心字母的大小写:使用<code>collections.Counter</code></p>
<pre><code>>>> from collections import Counter
>>> my_string = 'asdfssgAAatG'
>>> "".join(sorted([x+str(y) for x,y in Counter(my_string).items()],key=lambda x:my_string.index(x[0])))
'a2s3d1f1g1A2t1G1'
</code></pre>
<p>创建函数并返回它:</p>
<pre><code>>>> def count_it(my_string):
... return "".join(sorted([x+str(y) for x,y in Counter(my_string).items()],key=lambda x:my_string.index(x[0])))
...
>>> count_it('aabggtttf')
'a2b1g2t3f1'
>>> count_it('abc')
'a1b1c1'
</code></pre>
<p>使用<code>itertools.groupby</code>:</p>
<pre><code>>>> "".join([ x+str(len(list(y))) for x,y in itertools.groupby('aabggtttf')])
'a2b1g2t3f1'
</code></pre>