python-3.x - 计算每个字符串的出现次数并使用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
这是我想要的输出。
帮助任何人?(:
解决方案
你可以这样做:
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'
推荐阅读
- python - 嵌套相机 API
- php - php中午夜过去两次之间的分钟间隔
- javascript - 动画:`useNativeDriver` 未指定 ReactNativeBase 输入问题
- python - 下拉提交所选值的问题 - Django/Python
- c - 二维数组和for循环
- java - MacOS 中的 Java 捕获屏幕截图被阻止
- python - 根据另一个列表和附加条件修改一个列表
- r - R:插入符号包:Brier分数
- visual-studio-code - 扩展主机意外终止。代码:0 信号:null abstractExtensionService.ts:155
- python - 根据数据框中两列之间的差异对字典的值求和 - Python