{ }codelper
用字典计数自定义排序P0034

单词频率排名

给出一行由单个空格隔开的小写英文单词。
对每个不同的单词输出一行 "单词 次数"。
出现次数多的单词先输出;次数相同时按单词的字典序(a 在前;开头相同时短的在前)输出。

输入
单词数 1 到 1000,每个单词为 1 到 12 个小写英文字母
输出
不同单词的个数行,每行是单词和次数,用一个空格隔开
样例 1 · stdin
b a b a c
stdout
a 2
b 2
c 1
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

陷阱在次数相同时的顺序。
只按次数排序会保留首次出现的顺序;在 Python 中把 (次数, 单词) 用 reverse=True 排序,单词也会从 z 开始。
一次用两个标准:Python key=lambda kv: (-kv[1], kv[0]),JS b[1] - a[1] || (a[0] < b[0] ? -1 : 1),Java comparingByValue().reversed().thenComparing(comparingByKey()),C# OrderByDescending(...).ThenBy(..., StringComparer.Ordinal),C 在 qsort 比较函数中用 strcmp,C++ 给 std::sort 传 lambda。
计数:Python Counter,Java merge(w, 1, Integer::sum),C# GetValueOrDefault,JS 用 Map 而不是 {}(用空对象计数,"constructor" 会和 Object.prototype 上的冲突)。
C 没有字典,只能从头查找数组。
Craykon 用 字典() 计数,再像 键列表.排序(多的在前) 这样传入比较函数名(与 C# 的 Sort(Comparison) 相同:前者在先为负,后者在先为正)。

Pythonmain.py · 5 行
from collections import Counter counts = Counter(input().split())for word, count in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):    print(word, count)
JavaScriptmain.js · 5 行
const words = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);const counts = new Map();for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);const entries = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));console.log(entries.map(([w, c]) => `${w} ${c}`).join("\n"));
TypeScriptmain.ts · 6 行
import { readFileSync } from "node:fs";const words: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const counts = new Map<string, number>();for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);const entries: [string, number][] = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));console.log(entries.map(([w, c]) => `${w} ${c}`).join("\n"));
JavaMain.java · 21 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        Map<String, Integer> counts = new HashMap<>();        for (String w : in.readLine().trim().split("\\s+")) counts.merge(w, 1, Integer::sum);        List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());        entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed()                .thenComparing(Map.Entry.comparingByKey()));        StringBuilder out = new StringBuilder();        for (Map.Entry<String, Integer> e : entries) out.append(e.getKey()).append(' ').append(e.getValue()).append('\n');        System.out.print(out);    }}
C#Main.cs · 15 行
using System;using System.Collections.Generic;using System.Linq; class Program{    static void Main()    {        var counts = new Dictionary<string, int>();        foreach (string w in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries))            counts[w] = counts.GetValueOrDefault(w) + 1;        var sorted = counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key, StringComparer.Ordinal);        foreach (var kv in sorted) Console.WriteLine($"{kv.Key} {kv.Value}");    }}
C++main.cpp · 17 行
#include <algorithm>#include <iostream>#include <string>#include <unordered_map>#include <vector> int main() {    std::unordered_map<std::string, int> counts;    std::string w;    while (std::cin >> w) counts[w]++;    std::vector<std::pair<std::string, int>> entries(counts.begin(), counts.end());    std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) {        if (a.second != b.second) return a.second > b.second;        return a.first < b.first;    });    for (const auto& [word, count] : entries) std::cout << word << ' ' << count << '\n';}
Cmain.c · 33 行
#include <stdio.h>#include <stdlib.h>#include <string.h> struct Entry {    char word[13];    int count;}; static int by_count_then_word(const void *pa, const void *pb) {    const struct Entry *a = pa, *b = pb;    if (a->count != b->count) return b->count - a->count;    return strcmp(a->word, b->word);} int main(void) {    static struct Entry entries[1000];    int n = 0;    char w[13];    while (scanf("%12s", w) == 1) {        int i = 0;        while (i < n && strcmp(entries[i].word, w) != 0) i++;        if (i == n) {            strcpy(entries[n].word, w);            entries[n].count = 0;            n++;        }        entries[i].count++;    }    qsort(entries, n, sizeof entries[0], by_count_then_word);    for (int i = 0; i < n; i++) printf("%s %d\n", entries[i].word, entries[i].count);    return 0;}
Craykonmain.cray · 33 行
words = 控制台.读行().分割();counts = 字典();遍历 (w 在 words){    如果 (counts.包含(w))    {        counts[w] = counts[w] + 1;    }    否则    {        counts[w] = 1;    }}keys = counts.键列表;keys.排序(많은것먼저);遍历 (w 在 keys){    控制台.输出(w + " " + counts[w]);} // 개수가 많은 것 먼저, 같으면 사전 순많은것먼저(앞, 뒤){    如果 (counts[앞] != counts[뒤])    {        返回 counts[뒤] - counts[앞];    }    如果 (앞 < 뒤)    {        返回 -1;    }    返回 1;}