Python 试图保持角色的顺序

Python 试图保持角色的顺序,python,Python,目标是计算字符出现的次数,我想按原始字符串的相同顺序打印它 示例:你好 打印输出:h2e3l2o1t1 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

目标是计算字符出现的次数,我想按原始字符串的相同顺序打印它

示例:
你好

打印输出:
h2e3l2o1t1

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

但是由于某种原因,
位于第一个字符之后。

您可以通过列表跟踪输入的字符,该列表保留顺序:

s = "Hello there!"
s_list = s.lower().replace(" ","")
#print s_list
char_count = {}
chars = []
for i in range(0, len(s_list)):
    if s_list[i] not in char_count:
        char_count[s_list[i]] = 1
        chars.append(s_list[i])
    else: 
        char_count[s_list[i]] += 1

s2 = " "

for k in chars:
    print(k)
    if k in char_count:
        s2 += k + " " + str(char_count[k])
print(s2)

使用OrderedDict保留dict中的顺序

from collections import OrderedDict
a='Hello there!'

d=OrderedDict()
for i in a.lower():
    if(i not in [' ','!']):
        d[i]=d.get(i,0)+1
for i,c in d.items():
    print(i,c, end=' ')

你可以用很多方法来做。最简单的方法之一是从第二个列表中获取帮助,该列表以有序的方式保存字符。您的代码似乎是这样的:

s_list = s.lower().replace(" ","")
order_list = []
#print s_list
char_count = {}
for i in range(0, len(s_list)):
    if s_list[i] not in char_count:
        order_list.append(s_list[i])
        char_count[s_list[i]] = 1
    else: 
        char_count[s_list[i]] += 1

s = " "

for k in order_list:
    s += k + " " + str(char_count[k])
print s

有两种方法可以在对代码进行最小更改的情况下完成此操作:

  • 使用带有排序的
    dict
    s的Python版本,如PyPy、CPython 3.6+或任何Python 3.7+(谢谢!)。您必须稍微更改代码,因为在Python3中,
    print
    是一个函数
  • 不要使用
    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版本中,dicts不记得插入顺序。查看
OrderedCounter
配方。顺便说一句,在迭代
char\u count
的键
k
时检查
k
是否在
char\u count
中有点多余。或者任何3.7+实现@timgeb良好点;我忘了它现在是标准的一部分。