python - 通过python以特定方式计算嵌套数组的平均值?

标签 python arrays square

我需要一种方法来按以下方式计算嵌套数组(偶数或奇数)的平均值:

假设我们有这个数组(列表)(甚至 4*4):

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

输出必须是这样的

mylist = [[3,6],
[4,4]
]

基于此计算

1 + 6 + 2 + 5 / 4 = 3
5 + 6 + 6 + 8 / 4 = 6
7 + 2 + 4 + 4 / 4 = 4
8 + 1 + 7 + 3 / 4 = 4

如果我们有一个像这样的奇怪的嵌套数组,也会发生同样的事情

mylist = [[7,9,1],
[4,2,1],
[3,2,3]]

输出将是:

mylist = [[5,1],
[2,3]
]

基于上面相同的计算..

7 + 9 + 4 + 2 / 4 = 5
1 + 1 / 2 = 1
3 + 2 / 2 = 2
3 / 1 = 3

那么我们如何通过Python实现这个过程,请注意,我知道如何对每个数组进行正常平均,就像逐行增加每个数组的数字并除以它的计数..

 mylist = [[70,80,90],
[30,40,50],
[0,10,20],
[10,40,40]]
avglist = []
for x in mylist:
    temp = 0
    counter = 0
    for y in x:     
        temp = temp + y
        counter = counter + 1
    avglist.append(temp/counter)
    print()
print()
print(avglist)

但是在这个问题中..我面临着如何跳转到下一个数组然后返回到第一个数组等等的问题..

**

notice: it has to be a square array ( row length = column length )

**

最佳答案

好的,这是我的尝试。虽然有点冗长,但我认为很容易理解。

# helper func to split nested list (NxN matrix) into 4 quadrants
def split_mat(mat):
    n = len(mat)
    s = math.ceil(n/2)
    up_left  = [mat[i][j] for i in range(0, s) for j in range(0, s)]
    up_right = [mat[i][j] for i in range(0, s) for j in range(s, n)]
    bt_left  = [mat[i][j] for i in range(s, n) for j in range(0, s)]
    bt_right = [mat[i][j] for i in range(s, n) for j in range(s, n)]
    return [up_left, up_right, bt_left, bt_right]

# then the averages you want to calculate becomes trivial
def avg_mat(mat):  
    quadrants = split_mat(mat)
    avgs = [sum(q)//len(q) for q in quadrants]
    return [[avgs[0], avgs[1]], [avgs[2], avgs[3]]]
even_list = [
[1,6,5,6],
[2,5,6,8],
[7,2,8,1],
[4,4,7,3]]

print(avg_mat(even_list))
--------------------------------------------------
[[3, 6], [4, 4]]
odd_list = [
[7,9,1],
[4,2,1],
[3,2,3]]

print(avg_mat(odd_list))
--------------------------------------------------
[[5, 1], [2, 3]]

关于python - 通过python以特定方式计算嵌套数组的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585731/

相关文章:

python - 将 beautifulsoup 输出转换为矩阵

在另一个类中发送的 c# 数组发回零

dart - 如何在 Flutter 应用中实现支付?

javascript - 如何判断方形阅读器是否加密

javascript - 推送多个 json 数组 - javascript

swift - 如何制作方形视频?

Python - 将 JSON 对象转换为字典

python - 使用理解反向采样嵌套列表

python - 在python中导入其他文件和全局变量

python - Numpy 使用索引数组在另一个数组中累积一个数组