2

在一般意义上,我如何平均一个元组中的值,使得:

(1,2,3),(3,4,5)

变成:

(2,3,4)
4

3 回答 3

17

你可以zip这样使用:

In [1]: x = ((1, 2, 3), (4, 5, 6))

In [2]: [sum(y) / len(y) for y in zip(*x)]
Out[3]: [2, 3, 4]

另一种方法在元组中使用lambda超过 2 个元组并导致浮点数而不是整数:

>>> x = ((10, 10, 10), (40, 55, 66), (71, 82, 39), (1, 2, 3))
>>> print tuple(map(lambda y: sum(y) / float(len(y)), zip(*x)))
(30.5, 37.25, 29.5)
于 2012-09-13T18:39:28.853 回答
12
x = ((1,2,3),(3,4,5))

from numpy import mean  # or write your own mean function
tuple(map(mean, zip(*x)))
# (2.0, 3.0, 4.0)

或者:

from numpy import mean
tuple(mean(x, axis=0))
于 2012-09-13T18:37:20.110 回答
-1
  private Tuple<int, double> CalcuteAverageTulpeList(List<Tuple<int, double>> tupleParameters)
    {
        int totalLtGain = 0;
        double totalMeasured = 0;

        foreach (var tupleParameter in tupleParameters)
        {
            totalLtGain = totalLtGain + tupleParameter.Item1;
            totalMeasured = totalMeasured + tupleParameter.Item2;
        }
        int averageLtGain = totalLtGain / tupleParameters.Count();
        double averageMeasured = totalMeasured / tupleParameters.Count();
        return new Tuple<int, double>(averageLtGain, averageMeasured);
    }
于 2021-09-22T08:56:49.943 回答