【发布时间】:2020-12-11 13:09:02
【问题描述】:
我有这段代码可以对字符串中的字符进行排序并计算它的重复次数。
def char_repetition(str):
reps = dict()
word = [character.lower() for character in str.split()]
word.sort()
for x in word:
if x in reps:
reps[x] += 1
else:
reps[x] = 1
return reps
for x in char_repetition(str):
print (x,char_repetition(str)[x])
所以'1 2 3 2 1 a b c b a' 的输入会产生:
1 2
2 2
3 1
a 2
b 2
c 1
问题是我希望数字出现在输出的末尾,如下所示:
a 2
b 2
c 1
1 2
2 2
3 1
【问题讨论】:
-
您应该使用自定义比较器对字典进行排序:stackoverflow.com/questions/12031482/…
-
使用例如
word.sort(key=lambda i: (i.isdigit(), i))。