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>You can use the following nested list comprehension</p>

<pre><code>&gt;&gt;&gt; import math
&gt;&gt;&gt; [[math.hypot(point[0]-x, point[1]-y) for x,y in points] for point in points]
[[0.0, 2.8284271247461903, 5.656854249492381, 8.48528137423857],
 [2.8284271247461903, 0.0, 2.8284271247461903, 5.656854249492381], 
 [5.656854249492381, 2.8284271247461903, 0.0, 2.8284271247461903], 
 [8.48528137423857, 5.656854249492381, 2.8284271247461903, 0.0]]
</code></pre>

<p>This essentially makes a matrix with the distance from one point to any other point, where the row and column indexes are the "from" and "to" points, in which case the matrix will also be symmetric about the diagonal, and the diagonal will be all zeros.</p>

python loops