我有一个元组列表(表示 x-y 坐标),如果该坐标与前一个坐标(欧几里得距离)太接近,我希望将其删除。如果它符合标准并被删除,我希望随后根据其“新”相邻坐标检查原始坐标,然后如果它仍然太接近则将其删除。我需要重复这个过程,直到坐标达到所需的距离。然后我想移动到下一个坐标(该坐标最初可能是前面的多个坐标,没有删除)。
示例:
coordinateList=[x1,x2,x3,x4,x5,...]
if |x1-x2|<d:
remove x2
if |x1-x3|<d:
remove x3
...
until |x1-xn|>=d
then keep xn
coordinateList=[x1,xn,xn+1,xn+2...]
then
if |xn-xn+1|<d:
remove xn+1
etc.
etc.
我已经尝试过:
length=len(coordinateList)
while i < length:
if math.sqrt((coordinateList[i][0]-coordinateList[i+1][0])**2+(coordinateList[i][1]-coordinateList[i+1][1])**2)<50:
coordinateList.remove(coordinateList[i+1])
length-=1
else:
i+=1
我又拿回了原来的清单。
我也尝试过:
for i in range(1,maxRows):
j=i+1
norm=math.sqrt((coordinateList[i][0]-coordinateList[j][0])**2+(coordinateList[i][1]-coordinateList[j][1])**2)
if norm<50:
j=j+1
else:
coordinateList2.append(coordinateList[j])
但这仅适用于我的标准来列出原始列表中相邻的项目。
我在这里真的很挣扎,任何帮助将不胜感激
您预期的循环相当于:
coordinateList=[1, 2, 5, 6, 8, 10, 15, 15.1, 15.2]
d = 1
if len(coordinateList)>1:
i = 1
while i < len(coordinateList):
if abs(coordinateList[i]-coordinateList[i-1]) <= d:
coordinateList.pop(i)
else:
i += 1
print(coordinateList)
注意。演示中使用绝对距离,但如果需要,您可以使用
math.sqrt(…)
。
输出:
[1, 5, 8, 10, 15]
最后一种方法的变体,但与新列表中的最后一个元素进行比较(未测试):
coordinateList2 = []
for x in coordinateList:
if not coordinateList2 or distance(x, coordinateList2[-1]) < 50:
coordinateList2.append(x)
这里,
distance
是比较两个元素的函数。当前元素 x
仅与新列表 coordinateList2
中的最后一个元素(如果有)进行比较。这有点简单,而且应该更快,因为它不会从列表中间重复 remove
或 pop
。