Random selection of elements from python array

Possible duplicate:
How do I randomly select an item from a list using Python?

I have two arrays pool_list_X, pool_list_Y. Both have a numpy array as an item in the list. So basically

pool_list_x[0] = [1 2 3 4] # a multidimensional numpy array. 

and each pool_list_x element has a corresponding element in pool_list_y

 which is to say, that pool_list_x[i] corresponds to pool_list_y[i] 

Now. if I need to randomly select 10 items from list_x (and therefore the corresponding items in list_y). How can I do it. I can come up with a very naive way ... to randomly generate numbers. etc., but it’s not very effective .. what is the pythonic way to do this. Thanks

+4
source share
2 answers

Not sure I understand you one hundred percent, but I think using zip and random.sample might work:

 import random random.sample(zip(list_a,list_b), 10) 

A few short explanations:

  • zip will create a list of pairs, i.e. ensures that you select the appropriate items - if you select one, you will automatically get the other ( Zip([1,2,3],[4,5,6]) = [(1,4),(2,5),(3,6)] )
  • random.sample(l,n) randomly selects elements n from the list l
+20
source

There is a function that allows you to get a random element of this sequence:

 import random my_choice = random.choice(my_sequence) 

See the documentation for more details.

+4
source

Source: https://habr.com/ru/post/1403719/


All Articles