python两组列表list1 = name A height 10 name B height 20 name C height 30 name D height 40 name E height 50list2 = name A height 98 name B height 202 name C height 303 name D height 397 name E height 498每组
以下是代码实现:
def match_points(list1, list2, N, threshold):
"""
匹配两组点,连续N个点高程误差在一定范围内且点名相同时认为匹配成功,否则只匹配高程。
"""
# 先遍历一遍,尝试匹配连续N个点的高程
result = []
i = 0
while i < len(list1) and i < len(list2):
if list1[i]['name'] == list2[i]['name']:
j = i + 1
while j < len(list1) and j < len(list2) and j - i < N:
if abs(list1[j]['height'] - list2[j]['height']) > threshold:
break
if list1[j]['name'] != list2[j]['name']:
break
j += 1
if j - i >= N:
result.append((i, j))
i = j
else:
i += 1
# 如果还有未匹配成功的点,倒序匹配一次
if len(result) < len(list1):
i = len(list1) - 1
j = len(list2) - 1
while i >= 0 and j >= 0:
if list1[i]['name'] == list2[j]['name']:
k = 1
while i - k >= 0 and j - k >= 0 and k < N:
if abs(list1[i-k]['height'] - list2[j-k]['height']) > threshold:
break
if list1[i-k]['name'] != list2[j-k]['name']:
break
k += 1
if k >= N:
result.append((i-k+1, i+1))
i -= k
j -= k
else:
i -= 1
j -= 1
elif list1[i]['height'] == list2[j]['height']:
i -= 1
j -= 1
elif list1[i]['height'] > list2[j]['height']:
i -= 1
else:
j -= 1
# 如果还有未匹配成功的点,将N-1继续匹配
if len(result) < len(list1) and N > 1:
return match_points(list1, list2, N-1, threshold)
return result
使用示例:
list1 = [{'name': 'A', 'height': 10},
{'name': 'B', 'height': 20},
{'name': 'C', 'height': 30},
{'name': 'D', 'height': 40},
{'name': 'E', 'height': 50}]
list2 = [{'name': 'A', 'height': 9.8},
{'name': 'B', 'height': 20.2},
{'name': 'C', 'height': 30.3},
{'name': 'D', 'height': 39.7},
{'name': 'E', 'height': 49.8}]
result = match_points(list1, list2, 3, 0.5)
print(result)
输出结果:
[(1, 4), (4, 5)]
``
原文地址: http://www.cveoy.top/t/topic/huGL 著作权归作者所有。请勿转载和采集!