如何使用Python在网格中创建10个随机的x,y坐标 [英] How to create 10 random x, y coordinates in a grid using Python

查看:500
本文介绍了如何使用Python在网格中创建10个随机的x,y坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to create a 8x8 grid and distribute 10 coins in random positions on the grid. The problem I am facing is that the randint function will sometimes generate the same random co-ordinates and therefore only 9 or 8 coins are generated and placed on the grid. How can I make sure this doesn't happen? Cheers :) This is my code so far:

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))

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

I have included a while/else - as there must not be a coin in the bottom left corner of the grid

推荐答案

只有64种情况,因此可以将所有坐标生成为元组(x,y),然后可以使用random.sample直接具有10个唯一元素,因此您无需检查或重绘.

You only have 64 cases, so you can generate all coordinates as tuples (x,y) and then you can use random.sample to directly have 10 unique elements, so you don't have to check or redraw.

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))

这篇关于如何使用Python在网格中创建10个随机的x,y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆