11

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 element in the list. So basically

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

and every element of pool_list_x has corresponding element in pool_list_y

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

Now. if I have to randomly select 10 elements from list_x (and hence the corresponding elements to list_y). how do i do this. I can think of a very naive way.. randomly generate numbers. and stuff.. but that is not very efficient.. what is the pythonic way to do this. Thanks

4
  • Did you think of looking at the standard library? Maybe googling this or searching stackoverflow? Commented Mar 27, 2012 at 17:49
  • Like i said, i know the naive way.. but in this case.. i would have to generate a random number and check for collisions in order to make sure that same number is not generated twice and 10 is just an example.. i want to generate like 100k random numbers.. this method wont suffice. Commented Mar 27, 2012 at 17:52
  • Yes, it is true that before you ask any question on stackoverflow, you should perform a minimum of research which includes looking for existing answers on stackoverflow. Commented Mar 27, 2012 at 18:11
  • 4
    I don't think that this is actually an exact duplicate. This question asks how to select multiple elements, while the proposed duplicate is about selecting one element. Commented Mar 27, 2012 at 19:50

2 Answers 2

27

Not sure if 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)

Some short explanations:

  • zip will create a list of pairs, i.e. it ensures that you pick corresponding elements - if you pick one, you automatically get the other (Zip([1,2,3],[4,5,6]) = [(1,4),(2,5),(3,6)])
  • random.sample(l,n) randomly selects n elements from a list l
Sign up to request clarification or add additional context in comments.

Comments

5

There is a function allowing you to get the random element of the given sequence:

import random
my_choice = random.choice(my_sequence)

For details see the documentation.

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.