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

2024-05-29 10:56:22 发布

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

如何使用python将列表中的元素(距离列表)按照元素之间的距离(欧几里德距离,其中索引假定为角度)细分为组,如下面的示例所示。其中新列表必须以原始列表中的起始索引开始 enter image description here

附言: 在欧几里德距离中,我们需要一个角度来计算它。所以我假设角度是list的索引,例如list[0]=10 然后列出1=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)) 

Tags: 元素距离列表mathsincosfloatlist
1条回答
网友
1楼 · 发布于 2024-05-29 10:56:22

希望这能奏效:

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]

相关问题 更多 >

    热门问题