简体   繁体   English

在二维列表python上索引和打印正确值的麻烦

[英]trouble with indexing and printing proper values on a 2-d list python

I have a simple 2-D list containing x,y pairs. 我有一个简单的二维列表,包含x,y对。 I am making a program to find the two set of points with the shortest distance between them. 我正在编写一个程序来查找两组点之间的距离最短的点。

The list 'values' contains all of the distances, and I'm pretty sure that they are the right distances. 列表“值”包含所有距离,我很确定它们是正确的距离。

I want to print out the two points which created the minimum distance. 我想打印出创建最小距离的两个点。 It is obviously very easy to print out the minimum distance, yet printing out the two points is giving me trouble. 打印最小距离显然很容易,但是打印出两点却给我带来麻烦。

I need to keep track of which sets of points are creating which distances. 我需要跟踪哪些点集正在创建哪些距离。

I think that I will probably have to re-write this code and start fresh in order to accomplish what I want. 我认为我可能必须重新编写此代码并重新开始才能完成我想要的。 However, is there anyway to achieve this result with what I have? 但是,有什么可以用我所拥有的来达到这个结果的吗? If not, how do I do this? 如果没有,我该怎么做? How do I keep track of what index is being used? 如何跟踪正在使用的索引?

code: 码:

multiD = [[1,3],
[-1,-1],
[1,1],
[2,0.5],
[2,-1],
[3,3],
[4,2],
[4,-0.5]]

def distance(x1, y1, x2, y2):
    distance = ( (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))) ** 0.5)
    return distance

values = []
for [x1,y1] in multiD:
    for [x2,y2] in multiD:
        if [x1,y1] != [x2,y2]:
            diff = distance(x1,y1,x2,y2)
            values.append(diff)
from itertools import combinations

points = [
    [ 1,   3],   [-1, -1],   [ 1,  1],
    [ 2, 0.5],   [ 2, -1],   [ 3,  3],
    [ 4,   2],   [ 4, -0.5]
]

def dist(pair):
    (x1, y1), (x2, y2) = pair
    return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5

def main():
    pairs = combinations(points, 2)
    closest = min(pairs, key=dist)
    print("The closest pair is {} at {}.".format(closest, dist(closest)))

if __name__=="__main_":
    main()

produces 产生

The closest pair is ([1, 1], [2, 0.5]) at 1.118033988749895.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM