0

I have a list of GPS coordinates. I also have a function which compares two GPS coordinates and calculates a value.

I know I can create a nested loop to run the function on every pair, but this seem inelegant.

Is there a recommended way to run a comparison function on items in a list?

Thanks.

Tom Brock
  • 920
  • 7
  • 29
  • What do you mean by every pair? For `list(range(10))`, would it be 0 and 1, 2 and 3, 4 and 5, etc.? Or 0 and 1, 1 and 2, 2 and 3, etc.? Or 0 and 1, 0 and 2, 0 and 3... 1 and 0, 1 and 2, 1 and 3... etc.? – TigerhawkT3 Nov 29 '16 at 06:53
  • Thanks for your comment. I mean 0 and 1, 0 and 2, 0 and 3, 0 and 4, 1 and 2, 1 and 3, 1 and 4, 2 and 3, 2 and 4, 3 and 4. – Tom Brock Nov 29 '16 at 06:58

1 Answers1

1

You can use itertools.combinations:

>>> from itertools import combinations
>>> list(combinations([1,2,3,4,5],2))
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

This is iterable, so you can iterate and process your data.

>>> for first, second in combinations([1,2,3,4,5],2):
...     print first, second
...     # perform your operation with first and second

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57