统计项目频率
您好,我正在使用 Delphi,我有一个包含以下项目的字符串列表:
45
A15
015
A15
A15
45
我想处理它并制作第二个字符串列表,其中包含 每个元素出现的次数:
45 [2]
015 [1]
A15 [3]
我如何用Delphi做到这一点?
Hi I'm using Delphi and I have a StringList with this items:
45
A15
015
A15
A15
45
I want to process it and make a second stringlist that will have
the number of appearance of each element:
45 [2]
015 [1]
A15 [3]
How can I do this with Delphi?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用字典:
唯一的问题可能是结果出现的顺序完全随机,并且取决于哈希映射的内部工作。
感谢 daemon_x 提供完整的单元代码:
You could use a dictionary:
The only problem might be that the order in which the results appear is completely random and dependes on the inner working of the hash map.
Thanks to daemon_x for the full unit code:
对原始列表进行排序,
创建新列表
迭代排序列表以计算每个不同的项目
并将计数存储在结果列表的对象字段中(或者,如果您尚未使用它,只需将计数类型转换为指针并将其存储为对象)。
最后,再次迭代以将计数添加到字符串中
Sort the original list,
create a new list
iterate over the sorted list to count every different item
and store the a count in the objects field of the resulting list (or if you don't use it already, just typecast the count into a pointer and store it as the object).
finally, iterate again to add the count to the string
我在我的头上编写了这个代码,因为我现在还没有安装 Delphi。让我知道它对您有何作用。
Stringlist1 是包含项目的原始列表,stringlist2 为空,将用于存储您想要的内容。
I coded this on my head as I don't have Delphi installed as of now. Let me know how it works for you.
Stringlist1 is the original list with the items, stringlist2 is empty and will be used to store what you want.