首页 > 解决方案 > 计算每个字符串的出现次数并使用python并排打印eac编号和字符串

问题描述

使用 Python3

所以这是我的问题,说我有一个字符串

my_str="aaaaabbbbcccdde"

我想编写一个代码,给我一个输出

5a4b3c2d1e

我在书中看到了一段代码,可以自动完成一些类似但不完全一样的无聊的事情。

这是下面的代码:

my_str="aaaaabbbbcccdde"
count = {}
for character in my_str:
    count.setdefault(character, 0)
    count[character]+= 1
print(count)
for item in count:
    print(count[item], item)

这是它给我的输出:

{'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1}
5 a
4 b
3 c
2 d
1 e

不是

5a4b3c2d1e

这是我想要的输出。

帮助任何人?(:

标签: python-3.x

解决方案


你可以这样做:

count = {}
for char in my_str:
    count[char] = count.get(char,0) + 1
for item in count:
    print(count[item],item,sep='', end='')

5a4b3c2d1e

如果你需要一个班轮,你可以这样做:

''.join([str(my_str.count(i)) + i for i in sorted(set(my_str),key = my_str.index)])
Out: '5a4b3c2d1e'

推荐阅读