How to iterate over a list of coordinates and calculate the distance between them in Python

I have a list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but it's hard for me to write an algorithm that will iterate over the list and calculate the distance between the first node and any other node. eg,

ListOfCoordinates = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]

In this case, I need a for loop that will iterate over the list and calculate the distance between the first coordinate and the second coordinates, the distance between the first coordinate and the third coordinate, etc. I need an algorithm that will help me, then I will convert it to python code. Thanks

Thanks for the feedback. That was helpful.

+4
source share
3 answers

, - ( " , , ..." ), , itertools , .

from math import hypot

def distance(p1,p2):
    """Euclidean distance between two points."""
    x1,y1 = p1
    x2,y2 = p2
    return hypot(x2 - x1, y2 - y1)

from itertools import combinations

list_of_coords = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]

[distance(*combo) for combo in combinations(list_of_coords,2)]
Out[29]: 
[2.8284271247461903,
 5.656854249492381,
 8.48528137423857,
 11.313708498984761,
 14.142135623730951,
 2.8284271247461903,
 5.656854249492381,
 8.48528137423857,
 11.313708498984761,
 2.8284271247461903,
 5.656854249492381,
 8.48528137423857,
 2.8284271247461903,
 5.656854249492381,
 2.8284271247461903]

edit: . :

from itertools import repeat

pts = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]

[distance(*pair) for pair in zip(repeat(pts[0]),pts[1:])]
Out[32]: 
[2.8284271247461903,
 5.656854249492381,
 8.48528137423857,
 11.313708498984761,
 14.142135623730951]

, .

+5
In [6]: l = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]

In [7]: def distance(a, b):                              
    return (a[0] - b[0], a[1] - b[1])
   ...: 

In [8]: for m in l[1:]:                                  
    print(distance(l[0], m))
   ...:     
(-2, -2)
(-4, -4)
(-6, -6)
(-8, -8)
(-10, -10)

, distance .

0

distance, , , .

def distance(p1, p2):
    return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)

node node, , ListOfCoordinates:

for i in range(1, len(ListOfCoordinates)):
    # you can use print or return, depending on your needs
    print distance(ListOfCoordinates[0], ListOfCoordinates[i])
0

Source: https://habr.com/ru/post/1536610/


All Articles