有没有一种方法可以根据小数位对 array/list 中 python 的值进行动态分组?

Is there a way to dynamically group values of a an array/list in python based on their decimal places?

我有以下一维数组:

B = [8.55905955, 8.63646974, 21.7694643, 21,87843119, 21.92463355]

基于这个数组,我想要一个仅由相似值的平均值组成的新数组。对于上面显示的数组,它应该导致一个新数组,如:

B_new = [8.598, 21.858]

应该考虑什么:

B 中值的总数是可变的。应该分组的值的数量是可变的(可以是 2、3、4、5,甚至只有一个)。一组中考虑的值的阈值应基于连续值之间的距离,例如,[8.5、8.7、8.8] 应该是一组,而 [8.5、8.7、9.9、10.2] 应该导致两组,因为差异8.7 和 9.9 之间大于 1。

如有任何帮助,我们将不胜感激。

谢谢

简单的分步生成器函数:

def chunk_avg(array, min_gap=1):
    chunk = []
    for n in array:
        if chunk and chunk[-1] + min_gap < n:
            yield sum(chunk) / len(chunk)
            chunk.clear()
        chunk.append(n)
    if chunk:
        yield sum(chunk) / len(chunk)

list(chunk_avg([8.55905955, 8.63646974, 21.7694643, 21.87843119, 21.92463355]))
# [8.597764645000002, 21.857509679999996]
list(chunk_avg([8.5, 8.7, 9.9, 10.2]))
# [8.6, 10.05]
from more_itertools import split_when
from statistics import mean

B = [8.55905955, 8.63646974, 21.7694643, 21.87843119, 21.92463355]

B_new = [*map(mean, split_when(B, lambda x, y: y - x > 1))]