我试图从文本文件中的点列表中找到最近的一对点。我正在尝试遍历文件,然后将结果附加到一个空文件中,然后对该文件进行最短距离的排序。你知道吗
输入文件(文本)如下所示:
2 20 55 217 33 45 100 50 99 22 13 86 60 217 34 29 14 19 200 25 100 7
我的挑战是创建循环来读取文本文件中的每一对点。下面是我到目前为止想出的代码:
#empty List
list2 = []
#distance calculation for 2 closest points
def closest_point(coord1,coord2):
(x1, y1) = coord1
(x2, y2) = coord2
result1 = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
return list2.append(result1)
#reading input file with pairs of coordinates
with open('c:\\closepoints.txt') as my_new_file:
contents = my_new_file.read()
list = contents.split()
list1 = zip(list[::2], list[1::2])
list1 = set(list1)
print (list1)
更新:根据评论,这里有一个更有效的解决方案,可以打印与原始答案相同的输出:
(原始答案如下)
您还可以创建一个regex,将所有数字解析为
map
生成器对象。然后,您可以使用list unpacking来展开列表,并最终生成一个列表理解,将列表压缩为成对的,如果需要,可以丢弃最后一个元素。此代码将打印[(2, 20), (55, 217), (33, 45), (100, 50), (99, 22), (13, 86), (60, 217), (34, 29), (14, 19), (200, 25), (100, 7)]
:改编自this regex answer。你知道吗
相关问题 更多 >
编程相关推荐