我有一个问题,需要按频率对简单字符串进行排序(我输入一个字符串,需要输出一个按降序排列的已排序字符串)。
让我举个例子(原始单词包含4个e,2个s,1个t,1个r和1个d;因此这些会被排序):
In [1]: frequency_sort("treeseeds")
Out [1]: "eeeesstrd"
大多数在Stack Overflow上的解决方案都指出我应该使用sorted()
函数来获取结果,然而,它只能处理某些情况。
我编写了两个函数,本应该起作用,但是它们似乎都不能处理我的特定输入(见下文)。
第一个函数:
def frequency_sort(s):
s_sorted = sorted(s, key=s.count, reverse=True)
s_sorted = ''.join(c for c in s_sorted)
return s_sorted
第二个函数:
import collections
def frequency_sort_with_counter(s):
counter = collections.Counter(s)
s_sorted = sorted(s, key=counter.get, reverse=True)
s_sorted = ''.join(c for c in s_sorted)
return s_sorted
使用这两个函数,我的输出结果如下:
第一个输出结果是正常的:
In [1]: frequency_sort("loveleee")
Out [1]: "eeeellov"
第二个输出并不是很多。
In [2]: frequency_sort("loveleel")
Out [2]: "leleelov"
第三个输出完全混乱:
In [3]: frequency_sort("oloveleelo")
Out [3]: "oloeleelov"
可能出了什么问题?这与'o'和'l'字符有关吗?还是我漏掉了什么?