Python:如何在具有容差的列表中分组相似的列表并取平均值?

2024-06-07 23:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

输入-->;a=[[297151320]、[29315305]、[296151320]、[295162306]、[297160309]、[300158321]

I have a list inside a list. I need to group by the third element in the list a[i][2] with tolerance + or - 5

输出-->;a=[[297151320]、[293151318]、[296151321]、[295162306]、[297160309]、[300158305]

Later I need to take an average of each subgroup such as [297, 151, 320], [293, 151, 318], [296, 151, 321] = [(297+293+296)/3,(151+151+151)/3,(320+318+321)/3] simillarly for the next group

final output

最终输出-->;a=[[295151320]],[[297160307]]]

有人能帮忙吗?


Tags: orthetoingtbyhavewith
2条回答

对不起,我没有得到你想要的。因为每个列表的ur值不一致。但是,你是说像这样吗

a = [[297, 151, 320], [293, 151, 305], [296, 151, 320], [295, 162, 306], [297, 160, 309], [300, 158, 321]]
b = []
i = -1
for x in range(len(a)):
    if (x%3) == 0:
        b.append([])
        i += 1
    ave = int(sum(a[x])/len(a[x]))
    b[i].append(ave)
print(b)

输出: [[256, 249, 255], [254, 255, 259]]

一种方法是创建一个生成器函数来进行公差分组。此函数假定列表已排序,因此需要传入已排序的列表,或对其进行修改以在函数中进行排序。我相信有人会用itertools.groupby找到一种方法来做到这一点

def groupby_tolerance(lst, tolerance):
    result = [lst[0]]

    for prev, curr in zip(lst, lst[1:]):
        if curr[2] - prev[2] > tolerance:
            yield result
            result = []
        result.append(curr)

    yield result

然后在排序列表上调用此函数(按第3项):

from operator import itemgetter

a = [[297, 151, 320], [293, 151, 305], [296, 151, 320], [295, 162, 306], [297, 160, 309], [300, 158, 321]]

grouped = groupby_tolerance(sorted(a, key=itemgetter(2)), 5)

其中给出了分组:

[[[293, 151, 305], [295, 162, 306], [297, 160, 309]], [[297, 151, 320], [296, 151, 320], [300, 158, 321]]]

然后可以压缩相应的元素并计算平均值:

from statistics import mean

averages = [[mean(x) for x in zip(*group)] for group in grouped]

print(averages)

平均值:

[[295, 157.66666666666666, 306.6666666666667], [297.6666666666667, 153.33333333333334, 320.3333333333333]]

相关问题 更多 >

    热门问题