目标是计算字符出现次数,我想按照原始字符串的相同顺序打印它
示例:你好!
打印输出:h 2 e 3 l 2 o 1 t 1
s_list = s.lower().replace(" ","")
#print s_list
char_count = {}
for i in range(0, len(s_list)):
if s_list[i] not in char_count:
char_count[s_list[i]] = 1
else:
char_count[s_list[i]] += 1
s = " "
for k in char_count:
if k in char_count:
s += k + " " + str(char_count[k])
print s
但由于某种原因 !
出现在第一个字符之后。
最佳答案
有两种方法可以对代码进行最少的更改来实现此目的:
- 使用带有排序
dict
的 Python 版本,例如 PyPy、CPython 3.6+ 或任何 Python 3.7+(感谢 timgeb!)。您必须稍微更改代码,因为print
是 Python 3 中的一个函数。 不要使用
dict
,而是使用collections.OrderedDict
:import collections s_list = s.lower().replace(" ","") #print s_list char_count = collections.OrderedDict() for i in range(0, len(s_list)): ...
关于python - 尝试保持字符的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786004/