通过列C的总和划分字典中元素的最佳方法

时间:2015-07-13 19:15:07

标签: c# dictionary

我有一份整理词典:

        Dictionary<string, int[]> ret = new Dictionary<string, int[]>();
        int[] a = {1,2,3,4,5};
        int[] b = { 3, 6, 9, 10, 12 };
        int[] c = {2,3,3,5,6};
        ret.Add("abc", a);
        ret.Add("def", b);
        ret.Add("ghi", c);

对每列中的值求和然后除以总和的最佳方法是什么?例如,第一个值是1 / {1 + 3 + 2}

这是我尝试的但是我认为它按行而不是因为类型转换错误而无效

public static Dictionary<string, double[]> freq(Dictionary<string, int[]> rawct)
    {

        Dictionary<string, double[]> scores = new Dictionary<string, double[]>();


        foreach (KeyValuePair<string, int[]> kvp in rawct)
        {
            double[] percent = Array.ConvertAll(kvp.Value, x => (double)x);
            var total = (double)kvp.Value.Sum();

            var result = percent.Select(d => d / total);


            scores.Add(kvp.Key, kvp.value);
        }

        return scores;
    }

1 个答案:

答案 0 :(得分:1)

如果你想按列除,我认为你可以做到这一点(假设所有数组的大小相同,在本例中为5个):

Dictionary<string, double[]> scores = ret.ToDictionary(r=> r.Key,
                         r => r.Value.Select((v, index)=> 
                         (double)v / ret.Values.Sum(values=> values[index]) // this is sum the columns
                         ).ToArray());

输出:

abc
    0,166666666666667
    0,181818181818182
    0,2
    0,210526315789474
    0,217391304347826
def
    0,5
    0,545454545454545
    0,6
    0,526315789473684
    0,521739130434783
ghi
    0,333333333333333
    0,272727272727273
    0,2
    0,263157894736842
    0,260869565217391