justachap
justachap

Reputation: 343

python random sequence from list

If I had a list that ranged from 0 - 9 for example. How would I use the random.seed function to get a random selection from that range of numbers? Also how I define the length of the results.

import random

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = 10
random.seed(a)
length = 4

# somehow generate random l using the random.seed() and the length.
random_l = [2, 6, 1, 8]

Upvotes: 0

Views: 17717

Answers (3)

Skillmon
Skillmon

Reputation: 177

If you got numpy loaded, you can use np.random.permutation. If you give it a single integer as argument it returns a shuffled array with the elements from np.arange(x), if you give it a list like object the elements are shuffled, in case of numpy arrays, the arrays are copied.

>>> import numpy as np
>>> np.random.permutation(10)
array([6, 8, 1, 2, 7, 5, 3, 9, 0, 4])
>>> i = list(range(10))
>>> np.random.permutation(i)
array([0, 7, 3, 8, 6, 5, 2, 4, 1, 9])

Upvotes: 1

poke
poke

Reputation: 388023

Use random.sample. It works on any sequence:

>>> random.sample([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
[4, 2, 9, 0]
>>> random.sample('even strings work', 4)
['n', 't', ' ', 'r']

As with all functions within the random module, you can define the seed just as you normally would:

>>> import random
>>> lst = list(range(10))
>>> random.seed('just some random seed') # set the seed
>>> random.sample(lst, 4)
[6, 7, 2, 1]
>>> random.sample(lst, 4)
[6, 3, 1, 0]
>>> random.seed('just some random seed') # use the same seed again
>>> random.sample(lst, 4)
[6, 7, 2, 1]
>>> random.sample(lst, 4)
[6, 3, 1, 0]

Upvotes: 12

amehta
amehta

Reputation: 1317

import random

list = [] # your list of numbers that range from 0 -9

# this seed will always give you the same pattern of random numbers.
random.seed(12) # I randomly picked a seed here; 

# repeat this as many times you need to pick from your list
index = random.randint(0,len(list))
random_value_from_list = list[index]

Upvotes: 0

Related Questions