简体   繁体   English

二维列表中元素的平均值

[英]Average of elements in a 2d list

I have a list like the following:我有一个如下所示的列表:

[[1, 1], [7, 7], [20, 20], [9, 9], [-12, -12]] 

And I'm trying to have a new list which has the same number of lists inside, but changes the value of the elements by calculating the average of an element with the element after and before.我正在尝试创建一个新列表,其中包含相同数量的列表,但通过计算元素与前后元素的平均值来更改元素的值。 What do I mean by that ?: Let's say I have the sub-list sub = [7,7] at index 1. I want this list to be [9,9], because sub[1][0] + lst_before_sub[0][0] + lst_after_sub[1][0] = 7 + 1 + 20 = 28, and 28//3 = 9 (I want integer divison).我的意思是什么?:假设我在索引 1 处有子列表 sub = [7,7]。我希望这个列表是 [9,9],因为 sub[1][0] + lst_before_sub[ 0][0] + lst_after_sub[1][0] = 7 + 1 + 20 = 28,和 28//3 = 9(我想要整数除法)。

The ideal output would be:理想的输出是:

[[4, 4], [9, 9], [12, 12], [5, 5], [-1, -1]] 

I have currently this code:我目前有这个代码:

copy_l = copy.deepcopy(audio_data)
sub_list = []
for i in range(0, len(audio_data)-1):
    sub_data = []
    for j in range(2):
        if i == 0:
            audio_data[i][j] += int(audio_data[i+1][j] / 2)
            sub_data.append(audio_data[i][j])
        elif audio_data[i+1] == audio_data[-1]:
            audio_data[i+1][j] = int((audio_data[i+1][j]+audio_data[i][j])/2)
            sub_data.append(audio_data[i+1][j])
        else:
            audio_data = copy_l
            audio_data[i][j] = int((audio_data[i-1][j] + audio_data[i][j] + audio_data[i+1][j])/3)
            sub_data.append(audio_data[i][j])
    sub_list.append(sub_data)
print(sub_list)

where audio_data is the list [[1, 1], [7, 7], [20, 20], [9, 9], [-12, -12]] that I passed in.其中 audio_data 是我传入的列表 [[1, 1], [7, 7], [20, 20], [9, 9], [-12, -12]] 。

(I have separated the average calculation in three cases: - First element of the list: [1,1] so the average is just 1 + 7 // 2 (no element before [1,1]) - Last element of the list: [-12,-12] so the average is just -12 + 9 // 2 (no element after [-12,-12]) - All the elements in between ) (我在三种情况下分别计算平均值: - 列表的第一个元素:[1,1] 所以平均值只是 1 + 7 // 2([1,1] 之前没有元素) - 列表的最后一个元素: [-12,-12] 所以平均值只是 -12 + 9 // 2 ([-12,-12] 之后没有元素) - 中间的所有元素)

Problem is, my output (sub_list) is: [[4, 4], [9, 9], [12, 12], [-1, -1]] And it seems that [9,9] never turns into [5,5] Does someone have any idea how to achieve what I want, or even an idea to make it simpler ?问题是,我的输出(sub_list)是: [[4, 4], [9, 9], [12, 12], [-1, -1]]而且似乎 [9,9] 永远不会变成 [ 5,5] 有没有人知道如何实现我想要的东西,或者甚至是让它变得更简单的想法? I hope I was clear enough, if not feel free to ask me more details, thank you!我希望我说的够清楚了,如果没有,请随时问我更多细节,谢谢!

EDIT: I'm seeking a solution without numpy, list comprehension or zip.编辑:我正在寻找一个没有 numpy、列表理解或 zip 的解决方案。

Here is a way to do it:这是一种方法:

data = [[1, 1], [7, 7], [20, 20], [9, 9], [-12, -12]] 

out = []
for i in range(len(data)):
    first =  max(i -1, 0)  # don't have the start of the slice <0
    last = min(i + 2, len(data))  # neither beyond the end of the list
    mean = [sum(col) // (last-first) for col in zip(*data[first:last])]
    out.append(mean)

print(out)

# [[4, 4], [9, 9], [12, 12], [5, 5], [-2, -2]] 

We take slices of data around the current item.我们围绕当前项目获取数据切片。

Then, we zip the sublists, and we calculate the result on the first (resp. second) values of the sublists.然后,我们zip子列表,并计算子列表的第一个(或第二个)值的结果。

Also, note that using Python's integer division, we get -2 for -3//2 , not -1 as you got by rounding to the closest to 0. If you really want to do that, you'll have to use a custom function for the division.另外,请注意,使用 Python 的整数除法,我们得到-3//2 -2,而不是 -1,因为您通过四舍五入到最接近 0。如果您真的想这样做,您将不得不使用自定义为分区功能。

Here's a NumPy solution:这是一个 NumPy 解决方案:

import numpy as np

def mean3(data):
    return np.convolve(np.r_[data[:2].mean(), data, data[-2:].mean()], np.ones(3), 'valid')//3
>>> np.apply_along_axis(mean3, 0, audio_data)
array([[ 4.,  4.],
       [ 9.,  9.],
       [12., 12.],
       [ 5.,  5.],
       [-2., -2.]])

Or, if you prefer the int(x/y) definition of integer division:或者,如果您更喜欢整数除法的int(x/y)定义:

import numpy as np

def mean3(data):
   return (np.convolve(np.r_[data[:2].mean(), data, data[-2:].mean()], np.ones(3), 'valid')/3).astype(int)
>>> np.apply_along_axis(mean3, 0, audio_data)
array([[ 4,  4],
       [ 9,  9],
       [12, 12],
       [ 5,  5],
       [-1, -1]])

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

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