列表中元素按照出现频率排序,


例如:[4,6,2,2,6,4,4,4]→[4,4,4,4,6,6,2,2]

一: 先统计每个元素出现次数,然后按照出现次数进行逆向排序。

from collections import Counter
def frequency_count(list):
    counts = Counter(list)
    return sorted(list, key = lambda k : counts(k)*len(list)-list.index(k), reverse = True)

二:通过比较元组(-元素频率,元素index值)

def frequency_count(list)L
    return sorted(listed, key=lambda k:(-list.count(k),list.index(k)))

 

相关内容

    暂无相关文章

评论关闭