Python: Creating nested lists of floats using a for loop
<p>I am working with a list of points <code>[(1,2),(3,4),(5,6),(7,8)]</code>. I want to find the euclidean distance from each point to every other point in the list.</p>

<p>I then need a new list created to represent each point in the original list, and in the new list I will add the distances relating to that point only.</p>

<p>So far I have:</p>

<pre><code>for i in mat_ary1:
    points_dist_i = []
    for j in i:
        row = []
        x2 = [u[0] for u in i]
        y2 = [u[1] for u in i]
        # Calculate the distance from point j to all others
        for a in x2:
            dist_x_1 = pow((a - j[0]),2)     
        for b in y2:        
            dist_y_1 = pow((b - j[1]),2) 
            dist_xy_1 = float('{0:.2f}'.format((math.sqrt(dist_x_1 + dist_y_1))))

            for item in j: 
                if item not in row:
                    row.append(dist_xy_1)
                else:
                    continue
                points_dist_i.append(row) 
</code></pre>

<p>Each <code>i</code> in <code>mat_ary1</code> represents a list of points. With the loops I am using I appear to repeating the same calculations.</p>

<p>My input seems to be duplicating the rows:</p>

<pre><code>[[6.32, 6.32], [6.32, 6.32], [0.0, 0.0], [0.0, 0.0]]
[[11.4, 11.4], [11.4, 11.4], [0.0, 0.0], [0.0, 0.0]]
[[16.49, 16.49], [16.49, 16.49], [0.0, 0.0], [0.0, 0.0]]
[[14.32, 14.32], [14.32, 14.32], [0.0, 0.0], [0.0, 0.0]]
[[13.0, 13.0], [13.0, 13.0], [0.0, 0.0], [0.0, 0.0]]
[[11.66, 11.66], [11.66, 11.66], [0.0, 0.0], [0.0, 0.0]]
</code></pre>

<p>Scikit-learn has a function for this exact problem, and it will probably be  the fastest implementation if your array is large.</p>

<pre><code>&gt;&gt;&gt;&gt;from sklearn.metrics.pairwise import pairwise_distances
&gt;&gt;&gt;&gt;pairwise_distances(mat_ary1)
array([[ 0.        ,  2.82842712,  5.65685425,  8.48528137],
   [ 2.82842712,  0.        ,  2.82842712,  5.65685425],
   [ 5.65685425,  2.82842712,  0.        ,  2.82842712],
   [ 8.48528137,  5.65685425,  2.82842712,  0.        ]])
</code></pre>

python loops