我到目前为止:
def most_frequent(string): d = dict() for key in string: if key not in d: d[key] = 1 else: d[key] += 1 return d print most_frequent('aabbbc')
返回:
{'a': 2, 'c': 1, 'b': 3}
现在我需要:
扭转这一对
按降序排序
只打印出来的字母
我应该将此字典转换为元组还是列表?
这是一个单行答案
sortedLetters = sorted(d.iteritems(), key=lambda (k,v): (v,k))
这应该做得很好.
def frequency_analysis(string): d = dict() for key in string: d[key] = d.get(key, 0) + 1 return d def letters_in_order_of_frequency(string): frequencies = frequency_analysis(string) # frequencies is of bounded size because number of letters is bounded by the dictionary, not the input size frequency_list = [(freq, letter) for (letter, freq) in frequencies.iteritems()] frequency_list.sort(reverse=True) return [letter for freq, letter in frequency_list] string = 'aabbbc' print letters_in_order_of_frequency(string)