Search code examples
pythonlisttupleslist-comprehension

Comparing tuple elements across lists


I have two lists containing tuples of centroid coordinates...

current_centroids = [(924, 849), (734, 974), (360, 778), (400, 710), (963, 1067), (839, 440), (899, 88)]
prior_centroids = [(1096, 837), (522, 763), (898, 960), (563, 694), (1790, 720), (1080, 75), (1780, 713)]

I would like to generate paired tuples based on comparing the second element of each tuple in current_centroids with the second element of each tuple in prior_centroids and finding the resulting pair with the minimum absolute difference between the second elements.

For example, for (924, 849) in current_centroids, the tuple from prior_centroids with the minimum absolute difference (=12) when comparing the second elements is (1096, 837). I've been trying to figure this out using list comprehension, so that I could generate a final list in the format [((924, 849), (1096, 837)), .....]. I'm not using zip because the elements in each list aren't going to be corresponding, and they can have differing number of elements, even though in my example they are the same size.


Solution

  • Loop over current_centroids. For each element, use min() to find the element of prior_centroids with the minimum absolute difference between their [1] values.

    result = []
    for c1 in current_centroids:
        c2 = min(prior_centroids, key=lambda c: abs(c1[1] - c[1]))
        result.append((c1, c2))
    

    Results with your sample input:

    [((924, 849), (1096, 837)),
     ((734, 974), (898, 960)),
     ((360, 778), (522, 763)),
     ((400, 710), (1780, 713)),
     ((963, 1067), (898, 960)),
     ((839, 440), (563, 694)),
     ((899, 88), (1080, 75))]