【发布时间】:2020-04-18 20:39:37
【问题描述】:
这是一个让我难过的练习网站(checkio)。我需要创建一个函数,该函数接受一个列表并按频率(最多-> 最少)对其进行排序。没问题,但我的问题是,当呈现具有相同频率的元素时,还需要保留列表的原始顺序。
见下文。
import collections
from collections import Counter
def frequency_sort(items):
if len(items) > 0:
counts = collections.Counter(items)
print(sorted(items, key=lambda x: (counts[x], x), reverse=True))
else:
print([])
if __name__ == '__main__':
(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2]
(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex']
(frequency_sort([17, 99, 42])) == [17, 99, 42]
(frequency_sort([])) == []
(frequency_sort([1])) == [1]
数字 3 的输出错误,“[17, 42, 99]”。 我很迷茫如何解决这个问题。
【问题讨论】:
标签: python-3.x list sorting collections frequency