Python: Finding average of a nested list

后端 未结 3 2050
遇见更好的自我
遇见更好的自我 2021-02-13 13:01

I have a list

a = [[1,2,3],[4,5,6],[7,8,9]]

Now I want to find the average of these inner list so that

a = [(1+4+7)/3,(2+5+8)/         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 13:40

    If you have numpy installed:

    >>> import numpy as np
    >>> a = [[1,2,3],[4,5,6],[7,8,9]]
    >>> arr = np.array(a)
    >>> arr
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    >>> np.mean(arr)
    5.0
    >>> np.mean(arr,axis=0)
    array([ 4.,  5.,  6.])
    >>> np.mean(arr,axis=1)
    array([ 2.,  5.,  8.])
    

提交回复
热议问题