简体   繁体   English

在python中查找二维数组的平均值

[英]Finding average for a 2d array in python

For one of my coding practices, I need to find the sum and average of an array.对于我的编码实践之一,我需要找到数组的总和和平均值。 I've found a way to get the sum, however I've been struggling to get the code for the average working.我找到了一种方法来获得总和,但是我一直在努力获得平均工作的代码。 Right now I have my code without the average function:现在我的代码没有平均功能:

a = [[34,38,50,44,39], 
     [42,36,40,43,44], 
     [24,31,46,40,45], 
     [43,47,35,31,26],
     [37,28,20,36,50]]
     

def sumALL(x):
    sum = 0
    for r in range(len(x)):
        for c in range(len(x[0])):
            sum = sum + a[r][c]

    return sum


print("Sum of all the values: ", sumALL(a))

print("\n\n" + "The average is:  ")

I've found a few things online however they all either deal with numpy, in which the website does not support, or they don't work with the code I've made.我在网上找到了一些东西,但是它们要么处理 numpy,其中该网站不支持,要么不能使用我制作的代码。 I'd like to have the average as a function.我想将平均值作为函数。

Can't you just use sum() :你不能只使用sum()

sum(a,[])

And to average:并平均:

sum(a,[])/sum(len(r) for r in a)

If you are making a separate function for average如果您要为平均值制作单独的函数

def avg(lst):
     lst_el_avg = []
     for i in range(len(lst)):
             lst_el_avg.append(sum(lst[i])/len(lst))
     return sum(lst_el_avg)/len(lst)

Then reference it in your code as follows然后在您的代码中引用它,如下所示

print("\n\n" + "The average is:  " + avg(a))

One way to proceed is to flatten the 2d list to 1d list.一种方法是将 2d 列表展平为 1d 列表。 You can use itertools.chain() to achieve that.您可以使用itertools.chain()来实现这一点。 Then, you can use sum() and len() to find the average of the elements.然后,您可以使用sum()len()来查找元素的平均值。

import itertools

a = [[34,38,50,44,39], 
     [42,36,40,43,44], 
     [24,31,46,40,45], 
     [43,47,35,31,26],
     [37,28,20,36,50]]

flat_list = list(itertools.chain(*a))
avg = sum(flat_list) / len(flat_list)

print(avg)

Output输出


37.96

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM