社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python自定义比较器对特定列表进行排序

Subham Banerjee • 4 年前 • 211 次点击  

但需要注意的是,如果两个数字的计数相同,比如count(1)==count(2)。所以期望的输出是[2,1,6] 然后在输出数组中,2必须作为2>1在1之前。

我就是这么做的

  1. 测试用例数
def fun(l):
    d = {}
    for i in l:
        if i in d:
            d[i] += 1 
        else:
            d[i] = 1 
    d1 = sorted(d,key = lambda k: d[k], reverse=True)

    return d1
try:
    test = int(input())
    ans = []
    while test:
        l = [int(x) for x in input().split()]
        ans.append(fun(l))
        test -= 1
    for i in ans:
        for j in i:

            print(j, end = " ")
        print()    
except:
    pass
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57127
 
211 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Jorge Avila
Reply   •   1 楼
Jorge Avila    4 年前

我想这对你有帮助。我补充说 reverse 默认设置为的参数 True

代码如下:

from collections import defaultdict # To use a dictionary, but initialized with a default value

def fun(l, reverse = True):
    d = defaultdict(int)    
    # Add count
    for i in l:
        d[i] += 1 

    # Create a dictionary where keys are values
    new_d = defaultdict(list)
    for key,value in d.items(): 
        new_d[value].append(key)

    # Get frequencies
    list_freq = list(new_d.keys())
    list_freq.sort(reverse = reverse) #YOU CAN CHANGE THIS
    list_freq

    # Add numbers in decreasing order by frequency
    # If two integers have the same frequency, the greater number goes first
    ordered_list = []
    for number in list_freq:
        values_number = new_d[number]
        values_number.sort(reverse = reverse) # YOU CAN CHANGE THIS
        ordered_list.extend(values_number)

    return ordered_list

示例:

l = [1,2,2,1,6]
fun(l)
#Output [2,1,6]