如何使用Python在网格中创建10个随机x,y坐标

Mis*_*SJ 4 python random coordinates

我需要创建一个8x8网格,并在网格上的随机位置分配10个硬币.我面临的问题是randint函数有时会产生相同的随机坐标,因此只生成9或8个硬币并放在网格上.我怎样才能确保不会发生这种情况?干杯:)这是我的代码到目前为止:

from random import randint

grid = []
#Create a 8x8 grid
for row in range(8):
    grid.append([])
    for col in range(8):
        grid[row].append("0")

#create 10 random treasure chests
    #problem is that it might generate the same co-ordinates and therefore not enough coins
for coins in range(10):
    c_x = randint(0, len(grid)-1)
    c_y = randint(0, len(grid[0])-1)
    while c_x == 7 and c_y == 0:
           c_x = randint(0, len(grid)-1)
           c_y = randint(0, len(grid[0])-1)
    else:
        grid[c_x][c_y] = "C"

for row in grid:
print(" ".join(row))
Run Code Online (Sandbox Code Playgroud)

我已经包含了一段时间/其他 - 因为网格的左下角一定不能有硬币

Dee*_*ace 5

所以你希望生成10个随机唯一坐标?

您可以使用一组来验证:

cords_set = set()
while len(cords_set) < 10:
    x, y = 7, 0
    while (x, y) == (7, 0): 
        x, y = randint(0, len(grid) - 1), randint(0, len(grid[0]) - 1)
    # that will make sure we don't add (7, 0) to cords_set
    cords_set.add((x, y))
Run Code Online (Sandbox Code Playgroud)

这将生成一组表示(x, y)坐标的元组.

输出的几个例子print(cords_set):

{(5, 6), (7, 6), (4, 4), (6, 3), (7, 4), (6, 2), (3, 6), (0, 4), (1, 7), (5, 2)}

{(7, 3), (1, 3), (2, 6), (5, 5), (4, 6), (3, 0), (0, 7), (2, 0), (4, 1), (6, 5)}

{(1, 2), (1, 3), (6, 7), (3, 3), (4, 5), (4, 4), (6, 0), (1, 0), (2, 5), (2, 4)}
Run Code Online (Sandbox Code Playgroud)


pol*_*lku 5

您只有64个案例,因此您可以生成所有坐标作为元组(x,y),然后您可以使用random.sample直接拥有10个唯一元素,因此您不必检查或重绘.

import random
from itertools import product

g = [['0' for _ in range(8)] for _ in range(8)]

coord = list(product(range(8), range(8)))
for coins in random.sample(coord, 10):
    g[ coins[0] ][ coins[1] ] = 'C'

for row in g:
    print(' '.join(row))
Run Code Online (Sandbox Code Playgroud)