您好,我正在使用 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/