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

如何对存储词频的pair类型2D数组按第二个int元素降序排序

词频pair二维数组降序排序实现

核心逻辑:以每个元素中的词频数值为排序关键字,执行从大到小的降序排列即可实现高频词在前的效果。

示例输入输出

排序前原始数据

hello  3
jack   5
the    2
fish  10

排序后预期输出

fish  10
jack   5
hello  3
the    2

不同语言实现方案

Python 实现

如果你的二维数组存储结构为[[单词, 词频], ...],直接调用列表的sort方法指定排序规则即可:

# 原始词频数组
word_count_list = [["hello", 3], ["jack", 5], ["the", 2], ["fish", 10]]
# key指定取每个元素的第2位(词频)为排序依据,reverse=True开启降序
word_count_list.sort(key=lambda item: item[1], reverse=True)

# 输出验证
for item in word_count_list:
    print(f"{item[0]}\t{item[1]}")

C++ 实现

如果是pair<string, int>类型的vector数组,自定义排序比较函数传入std::sort即可:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

// 自定义比较规则:词频高的元素排在前面
bool sortByCountDesc(const pair<string, int>& a, const pair<string, int>& b) {
    return a.second > b.second;
}

int main() {
    vector<pair<string, int>> wordCountVec = {
        {"hello", 3},
        {"jack", 5},
        {"the", 2},
        {"fish", 10}
    };
    sort(wordCountVec.begin(), wordCountVec.end(), sortByCountDesc);

    // 输出验证
    for (auto& item : wordCountVec) {
        cout << item.first << "\t" << item.second << endl;
    }
    return 0;
}

扩展说明

如果遇到词频相同的场景,需要额外按单词字典序排序的话,只需要修改比较规则,增加词频相等时的判断逻辑即可,比如C++的比较函数可以调整为:

bool sortByCountThenWord(const pair<string, int>& a, const pair<string, int>& b) {
    if (a.second != b.second) {
        return a.second > b.second;
    }
    // 词频相同时按单词字典序升序排列
    return a.first < b.first;
}

内容的提问来源于stack exchange,提问作者jack the ripper

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:27:05