根据元素之间的距离将列表的元素分割成子组

segmentation of elements of a list into sub-groups according to the distance between it

如何使用 python 根据元素之间的距离(欧几里德距离,其中索引被假定为角度)将列表(距离列表)的元素细分为组,如下例所示.新列表必须从原始列表中的起始索引开始

PS: 在欧几里德距离中,我们需要一个角度来计算它。所以我假设角度是列表的索引,例如 list[0]=10 和 list1=12 计算欧几里德距离我们首先需要得到每个值的 X 和 Y

x1  =  (list[i] * math.cos(math.radians(float(i))))
 
y1 =  (list[i] * math.sin(math.radians(float(i))))

x2  =  (list[i+1] * math.cos(math.radians(float(i+1)))) 

y2=  (list[i+1] * math.sin(math.radians(float(i+1)))) 
distance= sqrt((x1 - x2) * (X - x2) + (posYd - y2) * (posYd - y2)) 

希望这有效:

import math
# initializing
result = []
vals = [10, 12, 11.5, 12.5, 135, 132, 133, 136, 2, 3, 4, 59, 60, 61, 66, 65, 63, 100, 102, 100]
max_distance = 9

temp = [0]  # Always the first index is zero
for i, val in enumerate(vals):
    if i != len(vals)-1:
        x1 = vals[i] * math.cos(math.radians(float(i)))
        y1 = vals[i] * math.sin(math.radians(float(i)))
        x2 = vals[i + 1] * math.cos(math.radians(float(i + 1)))
        y2 = vals[i + 1] * math.sin(math.radians(float(i + 1)))
        distance = math.sqrt((x1 - x2) ** 2 + (y2 - y1) ** 2)
        # Append the non-zero values
        if int(val) != 0:
            temp.append(val)
        if val != 0 and (distance > max_distance or vals[i+1] == 0):
            # There is 2 condition for ending a cluster
            # if present value !=0 and
            # con 1 : distance > max_distance
            # con 2 : the next value == 0
            result.append(temp)
        if vals[i+1] != 0 and (distance > max_distance or val == 0):
            # There is 2 condition for start a new cluster
            # if next value !=0 and
            # con 1 : distance > max_distance
            # con 2 : the present value == 0
            temp = [i + 1]
    else:
        last = val
temp.append(last)  # The final member
result.append(temp)  # The final cluster

for ls in result:
    print(ls)

结果:

[0, 10, 12, 11.5, 12.5]
[4, 135, 132, 133, 136]
[8, 2, 3, 4]
[11, 59, 60, 61, 66, 65, 63]
[17, 100, 102, 100]