用Python从列表中寻找最近点

2024-10-01 09:29:52 发布

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

我试图从文本文件中的点列表中找到最近的一对点。我正在尝试遍历文件,然后将结果附加到一个空文件中,然后对该文件进行最短距离的排序。你知道吗

输入文件(文本)如下所示:

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)

Tags: 文件withlistfilex1x2文本文件list2
1条回答
网友
1楼 · 发布于 2024-10-01 09:29:52

更新:根据评论,这里有一个更有效的解决方案,可以打印与原始答案相同的输出:

with open('c:\\closepoints.txt') as my_new_file:
    pairs = [int(x) for x in my_new_file.readline().strip().split()]
    list1 = list(zip(pairs[::2], pairs[1::2]))
    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)]

import re

with open('c:\\closepoints.txt') as my_new_file:
    contents = my_new_file.read()
    pairs = [*map(int, re.findall(r'\d+', contents))]
    list1 = [(pairs[i],pairs[i+1]) for i in range(0,len(pairs),2)]
    print (list1)

改编自this regex answer。你知道吗

相关问题 更多 >