Sorting 2D array by Mathematical Equation
<p>I have a 2D array list that contains (x,y), however I want to sort this list by the Equation of Minimum value of (square root of (x^2 + y^2)).</p>

<p>For example I have these four 2D lists:</p>

<pre><code>(20,10)
(3,4)
(5,6)
(1.2,7)
</code></pre>

<p>If I take the square root of each 2D array in this list and return the minimum of the sorted list, the output is:</p>

<pre><code>(3,4)
(1.2,7)
(6.5,4)
(5,6)
(20,10)
</code></pre>

<p>the Code :</p>

<pre><code>M=[ [20,10],[3,4],[5,6],[1.2,7],[6.5,4]]
</code></pre>

<p>s=np.sqrt(M)</p>

<p>a=[]</p>

<p>print s</p>

<p>for i in range(0,h):</p>

<pre><code>  for j in range(0,w):

     a[i] =s[i][j]+a[i]
</code></pre>

<p>Any ideas?</p>

<p>Use the built in sort method of a list:</p>

<pre><code>from math import sqrt

def dist(elem):
    return sqrt(pow(elem[0], 2) + pow(elem[1], 2))

def sorting_func(first, second):

    if dist(first) &lt; dist(second):
        return 1
    elif dist(second) &lt; dist(first):
        return -1
    else:
        return 0

bla= [(3, 2), (5, 4)]

bla.sort(sorting_func)

print bla
</code></pre>

python arrays sorting