gpt4 book ai didi

c# - 计算列表中所有整数的出现次数

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:15 25 4
gpt4 key购买 nike

我有一个包含大量数字(500,000+)的文本文件。

我想将所有唯一值添加到列表中并计算它在整个数据集中出现的次数。

所以像这样:

23232: 55656565 times
35354: 45452 times
45454: 74747 times

我在 C# 中的代码可以将所有出现的事件添加到列表中,但无法计算它们出现的频率:

private void CountUnique()
{
List<Double> source = new List<double>();
double sourceID = 0;

StreamReader file = new StreamReader("trace.txt")
while((line = file.ReadLine()) != null)
{
string[] words = line.split(' ');
sourceID = double.Parse(words[1]);
sourceList.Add(sourceID)
}
}

如何获得我想要的输出?

最佳答案

将 double 列表分组,然后使用组中的键和每个分组的计数将其放入字典中。

Dictionary<double,int> counts = source.GroupBy(d => d)
.ToDictionary( g => g.Key, g => g.Count());

这是一个简单的种子:

var source = Enumerable.Range(0,500)
.Select(i => ( i % 6 ) + 0.02).ToList(); // just simple doubles list

这是输出:

enter image description here

关于c# - 计算列表中所有整数的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30113509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com