Mean of elements from arbitrary number of nested lists

If I have a list, say:

foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]

I can get the mean of each element as follows:

[(a + b) / 2 for a, b in zip(foo[0], foo[1])]

or

import statistics
[statistics.mean(i) for i in zip(foo[0], foo[1])]

How can I do the same with an arbitrary number of nested lists in foo?

I tried several things but they do not work, for example:

[statistics.mean(i) for i in zip(list(foo))]

I would strongly prefer to just use comprehension.

3 answers

  • answered 2020-06-02 10:34 David Wierichs

    If you don't want to use any package:

    [statistics.mean([foo[j][i] for j in range(len(foo))]) for i in range(len(foo[0]))]
    

    With numpy it would be

    import numpy as np
    arr = np.array(foo)
    means = np.mean(arr,axis=0)
    

    edit

    without any package:

    [sum([foo[j][i] for j in range(len(foo))])/len(foo) for i in range(len(foo[0]))]
    

  • answered 2020-06-02 10:36 apoorva kamath

    Try this:

    import statistics
    foo =  [[4, 6, 2, 7], [1.2, 8.3, 9, 16]]
    x = [statistics.mean(i) for i in zip(*foo)]
    print(x)
    

  • answered 2020-06-02 10:36 dexter

    The following code should do the work:

    [sum(i)/len(i) for i in zip(*foo)]