pythonpython-3.xcoordinatesalternating

Alternating Directions in Python List - More Pythonic Solution


I feel this should be simple but I'm stuck on finding a neat solution. The code I have provided works, and gives the output I expect, but I don't feel it is Pythonic and it's getting on my nerves.

I have produced three sets of coordinates, X, Y & Z using 'griddata' from a base data set. The coordinates are evenly spaced over an unknown total area / shape (not necessarily square / rectangle) producing the NaN results which I want to ignore of the boundaries of each list. The list should be traversed from the 'bottom left' (in a coordinate system), across the x axis, up one space in the y direction then right to left before continuing. There could be an odd or even number of rows.

The operation to be performed on each point is the same no matter the direction, and it is guaranteed that the every point which exists in X a point exists in Y and Z as can be seen in the code below.

Arrays (lists?) are of the format DataPoint[rows][columns].

k = 0
for i in range(len(x)):
    if k % 2 == 0:  # cut left to right, then right to left
        for j in range(len(x[i])):
            if not numpy.isnan(x[i][j]):
                file.write(f'X{x[i][j]} Y{y[i][j]} Z{z[i][j]}')
    else:
        for j in reversed(range(len(x[i]))):
            if not numpy.isnan(x[i][j]):
                file.write(f'X{x[i][j]} Y{y[i][j]} Z{z[i][j]}')
    k += 1

One solution I could think of would be to reverse every other row in each of the lists before running the loop. It would save me a few lines, but probably wouldn't make sense from a performance standpoint - anyone have any better suggestions?

Expected route through list:

End════<══════╗
╔══════>══════╝
╚══════<══════╗
Start══>══════╝

Solution

  • Here's a variant:

    for i, (x_row, y_row, z_row) in enumerate(zip(x, y, z)):
        if i % 2:
            z_row = reversed(x_row)
            y_row = reversed(y_row)
            z_row = reversed(z_row)
        row_strs = list()
        for x_elem, y_elem, z_elem in zip(x_row, y_row, z_row):
            if not numpy.isnan(x_elem):
                row_strs.append(f"X{x_elem} Y{y_elem} Z{z_elem}")
        file.write("".join(row_strs))
    

    Considerations:

    There is no recipe for an optimization that will always perform better than any other. It also depends on the data that the code handles. Here's a list of things that I could think of, without knowing how the data looks like: