mno*_*tka 1 python sorting algorithm python-itertools
我有一个元素列表:[ 3, 3, 6, 6, 6, 5, 5, 8 ]需要按元素的频率对其进行排序才能得到这个:[ 6, 6, 6, 3, 3, 5, 5, 8 ]几个元素具有相同的频率按值排序.你能找到比这更短的路吗?
import collections
from operator import itemgetter, attrgetter
def freq_sort(arr):
counter=collections.Counter(arr)
com = sorted(counter.most_common(), key=itemgetter(1,0), reverse=True)
com = map(lambda x: [x[0]] * x[1], com)
return [item for sublist in com for item in sublist]
Run Code Online (Sandbox Code Playgroud)
试试这个
>>> old_list = [ 3, 3, 6, 6, 6, 5, 5, 8 ]
new_list = sorted(old_list, key = old_list.count, reverse=True)
>>> new_list
[6, 6, 6, 3, 3, 5, 5, 8]
Run Code Online (Sandbox Code Playgroud)