algorithm - 统计项目频率

标签 algorithm delphi delphi-2009

您好,我正在使用 Delphi,我有一个包含以下项目的 StringList:

45
A15
015
A15
A15
45

我想处理它并制作第二个字符串列表 每个元素出现的次数:

45 [2]
015 [1]
A15 [3]

我怎样才能用 Delphi 做到这一点?

最佳答案

你可以使用字典:

Frequencies := TDictionary <String, Integer>.Create;
try
  // Count frequencies
  for Str in StringList do
    begin
    if Frequencies.ContainsKey (Str) then
      Frequencies [Str] := Frequencies [Str] + 1
    else
      Frequencies.Add (Str, 1);
    end; 

   // Output results to console
   for Str in Frequencies.Keys do
     WriteLn (Str + ': ' + IntToStr (Frequencies [Str]));
finally
  FreeAndNil (Frequencies);
end;

唯一的问题可能是结果出现的顺序是完全随机的,并且取决于 HashMap 的内部工作方式。

感谢daemon_x完整的单元代码:

program Project1;

{$APPTYPE CONSOLE}

uses SysUtils, Classes, Generics.Collections;

var Str: String;
    StringList: TStrings;
    Frequencies: TDictionary <String, Integer>;

begin
  StringList := TStringList.Create;

  StringList.Add('45');
  StringList.Add('A15');
  StringList.Add('015');
  StringList.Add('A15');
  StringList.Add('A15');
  StringList.Add('45');

  Frequencies := TDictionary <String, Integer>.Create;

  try
  // Count frequencies
  for Str in StringList do
    begin
      if Frequencies.ContainsKey (Str) then
        Frequencies [Str] := Frequencies [Str] + 1
      else
        Frequencies.Add (Str, 1);
    end;

   // Output results to console
   for Str in Frequencies.Keys do
     WriteLn (Str + ': ' + IntToStr (Frequencies [Str]));

finally
  StringList.Free;
  FreeAndNil(Frequencies);
end;

end.

关于algorithm - 统计项目频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6276297/

相关文章:

c++ - 均匀填充大小不一的 "buckets"未排序列表的最有效方法是什么

delphi - 更改形状的方向

Delphi 2009 仅在一个单元的断点处停止

delphi - TListView.Clear 卡住了我的应用程序,我该如何修复它?

algorithm - 查找整数的位数

algorithm - 是否存在不包含最小/最大加权边的最小生成树?

java - 如果数据包含逗号,如何将其存储在 csv 中?

java - 德尔福: Constructing Abstract Class like Java

postgresql - 如何使用 Postgres 16 64 位连接到 Delphi 11.3 CE 32 位?

Delphi 2009 不分配自定义组件的事件