2

Assume I have the following 8x8 2D list:

[[0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [-1, 0, -1, 0, -1, 0, -1, 0], [0, -1, 0, -1, 0, -1, 0, -1], [-1, 0, -1, 0, -1, 0, -1, 0]] 

How do I get a random index for the value "1" for example ?

2
  • 3
    What have you tried? Also, I assume this is a generic python list and you're not using numpy? Commented Jan 20, 2018 at 22:22
  • Is this matrix always rectangular? Commented Jan 20, 2018 at 22:22

3 Answers 3

7

Here's a nice one-liner with a nested list comprehension:

import random random.choice([(i, j) for i, row in enumerate(x) for j, val in enumerate(row) if val == 1]) 

where x is your list. You just gather a list of indices (i, j) where val == 1, then randomly pick one.

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

Comments

4

If the list is rectangular (all elements are lists and these lists have the same length and the elements of these lists are numbers), we can boost the filtering process by using numpy instead:

from numpy import array, where from random import choice choice(array(where(a == 1)).T) 

In case a is not an numpy array yet, we can convert it with:

choice(array(where(array(a) == 1)).T) 

This then for instance returns:

>>> choice(array(where(a == 1)).T) array([1, 2]) 

In case we want the result to be a list or tuple, we can call the constructor, like:

>>> tuple(choice(array(where(a == 1)).T)) (1, 6) 

Comments

1

You could do something like:

indices = [] for row_idx in range(len(a)): for col_idx in range(len(a[row_idx])): num = a[row_idx][col_idx] if num == 1: indices.append((row_idx, col_idx)) import random rand_idx = random.randrange(0, len(indices)) print indices[rand_idx] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.