简体   繁体   中英

Grid plotting in Python with coordinates and a map image

I'm fairly new to using python and I'm seeking help on a small project I'm working on.

So firstly I want to make a 10x10 grid out of coordinates and then add a loop function that can randomly pick a cell and somehow store the cell coordinates it has picked without selecting the same cell twice.

So far I have come up with this.

x = 1
y = 1

scale = 10

nn = []

for x in range(1,scale+1):
    mm = []
    for y in range(1,scale+1):
        xy = [x,y]
        mm.append(xy)
        #print(xy)
        y=+1
    nn.append(mm)
    x=+1

Out:[[[1, 1],
  [1, 2],
  [1, 3],
  [1, 4],
  [1, 5],
  [1, 6],
    etc

The next part is where I'm struggling.

import random
r = random.randint(1,10)
x = 1
y = r

xy = [x,y]
print(xy)
while x < 10:

    # direction North=1, East=2, South=3
    if y == 1:
        dir = [random.randint(0,1),random.randint(0,1)]
    elif y == 10:
        dir = [random.randint(0,1),random.randint(-1,0)]
    else:
        dir = [random.randint(0,1),random.randint(-1,1)]

    xy = [(a + b) for (a, b) in zip(xy, dir)]

    x = xy[0]
    y = xy[1]

if xy == [(a + b) for (a, b) in zip(xy, dir)]:
    pass
else:
    print(xy)

Eventually I would like to plot the coordinates onto a grid and then put a map image over the grid.

This is my first question so please excuse mistakes and code quotes. Thanks in advance

From my understanding, you're trying to get non repetitive random sample from a grid of coordinates, This can be done much more easily like this:

import random
grid = [(x,y) for x in range(10) for y in range(10)] # grid points
randomset = random.sample(grid, 5) # get 5 random element from grid

Result:

>>> randomset
[(6, 6), (4, 7), (7, 7), (1, 7), (0, 3)] # each coordinate will be unique.

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