You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python整数列表按频率降序、同频率按数值降序排序问题

按「频率降序+数值降序」排序字典键的实现方案

我是Python新手,需要处理一个整数列表:先统计每个整数的出现频率,再按以下规则排序提取键:

  • 优先按出现频率从高到低排序
  • 若多个整数频率相同,则数值更大的排在前面

我已经完成了频率统计,但排序时无法处理同频率的数值排序。当前代码及输出如下:

def frequency(requests):
    freq = {}
    for x in requests:
        if (x in freq):
            freq[x] += 1
        else:
            freq[x] = 1
    print(freq)   # provides expected result
    

#my attempt to sort dictionary and extract required values  
    sorted_freq = dict(sorted(freq.items(), key=lambda x:x[1], reverse=True))
    print(sorted_freq) #printing the keys at this stage doesn't factor in if the key is bigger/smaller for items with same frequency
    print(sorted_freq.keys())
    return


requests = [2,3,6,5,2,7,2,3,6,5,2,7,11,2,77] #example of request

frequency(requests)

当前输出:

freq = {2: 5, 3: 2, 6: 2, 5: 2, 7: 2, 11: 1, 77: 1}
sorted_freq = {2: 5, 3: 2, 6: 2, 5: 2, 7: 2, 11: 1, 77: 1}
sorted_freq.keys = [2, 3, 6, 5, 7, 11, 77]

我期望得到的键列表是[2, 7, 6, 5, 3, 77, 11],求最优解决方法。


核心修改:调整排序的key函数

Python的sorted()支持用元组作为排序键,会按元组内元素的顺序依次比较。我们需要同时指定两个排序维度:

  1. 频率降序:用频率的相反数(或配合reverse=True)
  2. 数值降序:用数值的相反数(或配合reverse=True)

方法一:使用负数值实现升序排序等效降序

修改排序逻辑,直接生成目标键列表(无需转成字典):

def frequency(requests):
    freq = {}
    for x in requests:
        if x in freq:
            freq[x] += 1
        else:
            freq[x] = 1
    print(freq)  

    # 按「频率降序→数值降序」排序
    sorted_items = sorted(freq.items(), key=lambda item: (-item[1], -item[0]))
    # 提取排序后的键
    sorted_keys = [item[0] for item in sorted_items]
    print(sorted_keys)
    return sorted_keys


requests = [2,3,6,5,2,7,2,3,6,5,2,7,11,2,77]
frequency(requests)

输出:

[2, 7, 6, 5, 3, 77, 11]

方法二:配合reverse=True简化写法

也可以用正序的排序键,再通过reverse=True反转整体顺序:

sorted_items = sorted(freq.items(), key=lambda item: (item[1], item[0]), reverse=True)

效果和方法一完全一致,原理是:先按频率升序、数值升序排序,再整体反转成频率降序、数值降序。

进阶优化:用collections.Counter简化频率统计

Python标准库的Counter可以一键完成频率统计,代码更简洁:

from collections import Counter

def frequency(requests):
    freq = Counter(requests)
    print(dict(freq))  # 输出和手动统计一致

    sorted_items = sorted(freq.items(), key=lambda item: (-item[1], -item[0]))
    sorted_keys = [item[0] for item in sorted_items]
    print(sorted_keys)
    return sorted_keys

内容的提问来源于stack exchange,提问作者newpythonstudent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:40:40