In Python, what's the best way to get the closest integers for two dimensions?
<p>I have a list of 2 dimensional tuples, unsorted, and of <code>n</code> size. I want to find which tuple has the closest dimensions to X and Y. What's the best way to do this?</p>

<pre><code>target = (75, 75)
values = [
    (38, 61),
    (96, 36),
    (36, 40),
    (99, 83),
    (74, 76),
]
</code></pre>

<p>Using the <code>target</code> and <code>values</code>, the method should produce the answer <code>(74, 76)</code>.</p>

<p><strong>Edit</strong></p>

<p>The <a href="http://stackoverflow.com/a/12697090/28360">answer below</a> lead me to this exact method, for anyone who lands here:</p>

<pre><code>def distance(item, target):
    return ((item[0] - target[0]) ** 2 + (item[1] - target[1]) ** 2) ** 0.5

best = min(values, key=lambda x: distance(x, target))
</code></pre>

<p>This is a <a href="http://en.wikipedia.org/wiki/Cartesian_coordinate_system#Distance_between_two_points" rel="nofollow">Cartesian Distance</a> problem.</p>

<ol>
<li>First take the square of the test value's <code>x</code> minus the optimal <code>x</code> value.</li>
<li>Then take the square of the test value's <code>y</code> minus the optimal <code>y</code> value.</li>
<li>Finally take the square root of step 1 plus step 2, which gives you the distance.</li>
<li>Apply this to all items in the list, and the lowest number (using the <code>min</code> function) will give you the best fit.</li>
</ol>
