如何计算列表中每n个数的平均值

时间:2015-03-23 16:26:55

标签: c#

有一个数字列表,我想取每个n(例如5,10等)元素,计算它们的平均值并将平均值放在一个新列表中。举个例子,假设我们有以下列表: 1,2,3,4,5,6,7,8 现在我们计算每2个元素的平均值,我们将得到以下列表作为输出: 1.5,3.5,5.5,7.5 我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:2)

您可以使用for循环和Enumerable.Average

var averages = new List<double>();
for (int i = 0; i < ints.Length; i += 2)
{
    int thisInt = ints[i];
    int nextInt = i == ints.Length - 1 ? thisInt : ints[i + 1];
    averages.Add(new[] { thisInt, nextInt }.Average());
}

这是一种适用于任何长度的动态方法:

int take = 2;
for (int i = 0; i < ints.Length; i += take)
{
    if(i + take >= ints.Length)
        take = ints.Length - i;
    int[] subArray = new int[take];
    Array.Copy(ints, i, subArray, 0, take);
    averages.Add(subArray.Average());
}

答案 1 :(得分:1)

这个问题只是测试你对迭代和模数运算符的使用。 Modulus为您提供除法的余数,您可以使用它来检查迭代数组时当前数字是否应包含在平均值中。这是一个示例方法;

public float nthsAverage(int n, int[] numbers)
{
     // quick check to avoid a divide by 0 error
     if (numbers.Length  == 0)
        return 0;

     int sum = 0;
     int count = 0;
     for (int i = 0; i < numbers.Length; i++)
     {
         // might want i+1 here instead to compensate for array being 0 indexed, ie 9th number is at the 8th index
         if (i % n == 0)
         {
              sum = sum + numbers[i];
              count++; 
         }
     }
     return (float)sum / count;
}

答案 2 :(得分:0)

public List<double> Average(List<double> number, int nElement)
    {
        var currentElement = 0;
        var currentSum = 0.0;

        var newList = new List<double>();

        foreach (var item in number)
        {
            currentSum += item;
            currentElement++;

            if(currentElement == nElement)
            {
                newList.Add(currentSum / nElement);
                currentElement = 0;
                currentSum = 0.0;
            }
        }
        // Maybe the array element count is not the same to the asked, so average the last sum. You can remove this condition if you want
        if(currentElement > 0)
        {
            newList.Add(currentSum / currentElement);
        }

        return newList;
    }