简体   繁体   中英

how to get all coordinates in the rectangle between two coordinates?

say i have a rectangle, and its top-left and bottom-right coordinates are A(0,0) and B(2,3) respectively. is there a method/formula that i can use to get all the coordinates inside this rectangle? I want my output to be like this if the input was these two coordinates:

input: [(0, 0), (2, 3)]
output: [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2), (0, 3,) (1, 3,) (2, 3)]

also, a python 3 implementation would be greatly appreciated, although not necessary.

thanks

EDIT: full story: i'm using python, and at first i thought i could achieve what i want by getting all the values between x1 and x2, y1 and y2. so for example i have x = 0, x = 1, x = 2 and y = 0, y = 1, y = 2, y = 3, but i honestly don't know where to go from there, or if this is correct in the first place. i thought i could get all the coordinates by somehow getting all the coordinates with y = 0 with different x values, then all the coordinates with y = 1... but i can't seem to wrap my head around a way of doing this. any help is appreciated, thanks.

One thing you could do is make a list of all x coordinates inside the rectangle [ x1..x2 ] and all y coordinates inside the rectangle [ y1..y2 ] and then take the Cartesian product of the two lists using itertools :

import itertools
...
input = [(0, 0), (2, 3)]
x_coords = [x for x in range(input[0][0], input[1][0] + 1)]
y_coords = [y for y in range(input[0][1], input[1][1] + 1)]
output = list(itertools.product(x_coords, y_coords))

If you don't want to use itertools to compute the product, you could also easily use a for loop or a list comprehension to do it instead, which is roughly equivalent to what itertools is doing behind the scenes anyway:

output = [(x, y) for x in x_coords for y in y_coords]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM