user2629628
user2629628

Reputation: 141

Random choice of of item in list with condition

I'm wondering if it's possible to do random.choice() for a list of lists and only pick a coordinate which is 0. Also is it possible two then save the randomly picked coordinate to a variable?

I.e I have a list of lists like so:

[[0, 2, 0, 0, 0],
 [0, 0, 0, 0, 1],
 [0, 0, 1, 2, 0],
 [0, 2, 0, 0, 0],
 [0, 0, 0, 0, 0]]

And I only want to pick those coordinates which is 0, and then save that coordinate to variable.

Thanks.

Upvotes: 0

Views: 497

Answers (2)

zarpetkov
zarpetkov

Reputation: 11

Random Integer can be as big as you want - well above the Integer level actually, not only 0, 1, and 2. Here is a cut/paste:

random.nextOct = 223,372,036,854,775,807,147,483,647

You just have to override the Random Class. And inside impose the condition.

Here is a link:

https://cyberconfidential.net/Comparisson1.html#HOW

Upvotes: 0

Corralien
Corralien

Reputation: 120559

Use comprehension to get coordinates of items equals to 0:

import random

L = [[0, 2, 0, 0, 0],
     [0, 0, 0, 0, 1],
     [0, 0, 1, 2, 0],
     [0, 2, 0, 0, 0],
     [0, 0, 0, 0, 0]]

coords = [(x, y) for x, l in enumerate(L) for y, i in enumerate(l) if i == 0]

x, y = random.choice(coords)
>>> L[x][y]
0

Upvotes: 2

Related Questions