我怎样才能把它分成两组,使输出为 [5.0, 5.2, 5.1], [4.0, 4.05, 4.1] ?我确信每组中的每个值都在它的伙伴的0.2以内。为这种分离指定一个阈值的最佳方式是什么?

以下是我到目前为止所尝试的。

unique_values = []
    for x in range(len(lst)):
        isInList=False
        for y in range(len(unique_values)):
            if compare_threshold(lst[x], unique_values[y]): #returns true if the two values are within the threshold
                isInList=True
        if isInList == False:
            unique_values.append(lst[x])
    print(unique_values)

这给了我一个列表中的单一独特点。

[55.02123905, 55.02167612, ... 137.0536191, 137.0536604] (118 values)

Output:

[55.02123905, 57.03325912, 67.0292289, 69.0339192, 71.01344708, 92.02611874, 94.04178177, 109.054014, 112.0537901, 119.0396714, 120.0424827, 136.0683814, 137.0527245]
    
3 个评论
到目前为止,你都试过什么?
另外,什么是组别,截止到四舍五入为int?
Omni
你说的 "为这种分离指定一个阈值的最佳方式是什么?"是什么意思?0.2是比较2个连续条目的阈值吗?
python
algorithm
Daniel C
Daniel C
发布于 2019-12-07
2 个回答
Paddy3118
Paddy3118
发布于 2019-12-07
已采纳
0 人赞同

组的最大尺寸为0.2。 需要_entier来解决浮点数的精度问题。

In [183]: def grouper(x, delta=0.2, _entier=1e-6):
     ...:     out, part = [], []
     ...:     for item in sorted(x):
     ...:         if not part:
     ...:             part = [item]
     ...:         elif item - part[0] <= delta + _entier:
     ...:             part.append(item)
     ...:         else:
     ...:             out.append(part)
     ...:             part = [item]
     ...:     if part:
     ...:         out.append(part)
     ...:     return out
In [184]: grouper(lst)
Out[184]: [[4.0, 4.05, 4.1], [5.0, 5.1, 5.2]]
    
@kaya3: 对不起,我复制了一个以前的开发版本。现在正确的版本是他们的。
我们可以看到,如果列表中有5.0、5.1、5.3和5.2,就会产生[[5.0, 5.1, 5.2], [5.3]]。有些人可能会说,最好把5.2和5.3放在一起,也就是说,如果小于0.2就使用分组规则。它只影响到恰好0.2出的项目的分组,作为一个角落案例。
Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev
发布于 2019-12-07
0 人赞同

Try this :

def grouper(list_, threshold):
    list_.sort()
    prev = None
    group = []
    for item in list_:
        if not prev or item - prev <= threshold:
            group.append(item)
        else:
            yield group
            group = [item]
        prev = item
    if group:
        yield group
lst = [5.0, 5.2, 4.0, 4.1, 4.05, 5.1]
output = list(grouper(lst, threshold=0.2))