Suppose that I have the following array or arrays:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 5, 6, 7]]
What's the best way to loop into the main array and randomly extract one number from each sub-array every time and create another array with them? For instance, in the first pass, the result would be:
[2,5,6]
The second pass could be:
[8,0,7]
etc. At this stage I don't have any clues how to do it.
CodePudding user response:
If you have python lists, you can use random.choice
in a list comprehension:
L = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 5, 6, 7]]
from random import choice
out = [choice(l) for l in L]
example output:
[3, 0, 5]
variant
Imagine you want to pick each item only a single time in each iteration, you could also use pop
on a random position:
L = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 5, 6, 7]]
for i in range(6):
print([l.pop(np.random.randint(len(l))) for l in L])
Obviously, here you cannot have a number of iterations greater than the length of the shortest sublist
example output:
[5, 4, 0]
[2, 2, 6]
[3, 5, 7]
[0, 1, 1]
[4, 3, 2]
[9, 0, 3]