Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested for loop not looping on the first set, Python

I have written this code in python. In the end I would like to use this to get the indices to cut up a 100×100 matrix into squares that overlap by 10. However, at the bottom there is a nested loop and the y values print how I think they should but not the x-values, the x-values never change… Can anyone help? Thanks

x_split = np.linspace(0, 100, 4 + 1, dtype=int)
x_start = x_split[:-1] - 5
x_start[0] = 0
x_end = x_split[1:] + 5
x_end[-1] = 100

y_split = np.linspace(0, 100, 4 + 1, dtype=int)
y_start = y_split[:-1] - 5
y_start[0] = 0
y_end = y_split[1:] + 5
y_end[-1] = 100

x_inds = zip(x_start, x_end)
y_inds = zip(y_start, y_end)

i = 0
for start_x, end_x in x_inds:
    for start_y, end_y in y_inds:
        i += 1
        print(f"i = {i}")
        print(f"x = {start_x} {end_x}")
        print(f"y = {start_y} {end_y}")
        print("")

Current output:

i = 1
x = 0 30
y = 0 30

i = 2
x = 0 30
y = 20 55

i = 3
x = 0 30
y = 45 80

i = 4
x = 0 30
y = 70 100

And then stops. I want to to continue…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i = 5
x = 20 55
y = 0 30

i = 6
x = 20 55
y = 20 55

...

>Solution :

zip(y_start, y_end) returns an iterator. After the first series of Xs, y_inds is exhausted and yields no more values for the subsequent values of X.

Make it y_inds a list, so it can be reused on subsequence X rows:

*y_inds, = zip(y_start, y_end)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading