Reputation: 77
Consider a list with various points
l=[(point1,point2),(point3,point4),....,(point 2n-1, point 2n)]
now we have a function that calculates the distance between point
distance(point1,point2)
How to apply the function for all the points in the list?
Upvotes: 1
Views: 58
Reputation: 17322
you can use a simple for
loop:
result = []
for p1, p2 in l:
result.append(distance(p1,p2))
Upvotes: 0
Reputation: 73450
You can use itertools.starmap
:
from itertools import starmap
list(starmap(distance, l))
or just a list comprehension:
[distance(*p) for p in l] # hence the name `starmap`
if you are in fact looking for the distances of any pair of points (coordinate pairs), you can use itertools.product
:
from itertools import starmap, product
list(starmap(distance, product(l, repeat=2)))
# or
[distance(*points) for points in product(l, repeat=2)]
If you don't want to pair points with themselves and don't care about order (after all, "distance" indicates symmetry), use combinations
:
from itertools import starmap, combinations
list(starmap(distance, combinations(l, 2)))
Upvotes: 4
Reputation: 10960
Zip with a sliced list and use list comprehension
distances = [distance(p1, p2) for p1, p2 in list(zip(l, l[1:]))]
What does list(zip(l, l[1:]))
do? It combines two adjacent elements
>>> l = [(0,1), (1,2), (2,3), (3,4)]
>>> list(zip(l, l[1:]))
[((0, 1), (1, 2)), ((1, 2), (2, 3)), ((2, 3), (3, 4))]
Upvotes: 0