Tom Brock Tom Brock - 5 days ago 5
Python Question

How to run a comparison function on items in a list?

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.

Answer

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
Comments