1

I currently have a 2d array generated by this code:

for y in range(width):
    self.grid.append([])
    for x in range(width):
        self.grid[y].append(Cell(x, y))

If I want to select a random cell, how would I go about it? random.choice doesn't seem to be working.

2

2 Answers 2

2

You could do something like

yCoord = random.randrange(width)
xCoord = random.randrange(width)
randomCell = self.grid[yCoord][xCoord]

If you do want to use random.choice, you'll have to use it twice, as the first call will return an array of Cells, then the second one will return a cell element.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use:

s = list[random.randint(0, len(list) - 1]
rn = s[random.randint(0, len(s) - 1]

You need to use double lines as you need to find the length of the sublist. I don't know or think any direct way exists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.