Selecting A Random List Element Of Length N In Python
I know you can use random.choice to choose a random element from a list, but I am trying to choose random elements of length 3. For example, list1=[a,b,c,d,e,f,g,h] I want the ou
Solution 1:
You want a sample; use random.sample()
to pick a list of 3 elements:
random.sample(list1, 3)
Demo:
>>> import random
>>> list1 = ['a', 'b', 'c' ,'d' ,'e' ,'f', 'g', 'h']
>>> random.sample(list1, 3)
['e', 'b', 'a']
If you needed a sublist, then you are stuck with picking a random start index between 0 and the length minus 3:
def random_sublist(lst, length):
start = random.randint(len(lst) - length)
return lst[start:start + length]
which works like this:
>>>defrandom_sublist(lst, length):... start = random.randint(len(lst) - length)...return lst[start:start + length]...>>>random_sublist(list1, 3)
['d', 'e', 'f']
Solution 2:
idx = random.randint(0, len(list1)-3)
list1[idx:idx+3]
Solution 3:
If you want the result to wrap around to the start of the list you can do:
idx = randint(0, len(list1))
(list1[idx:] + list1[:idx])[:3]
Solution 4:
If all you want is a random subset of the original list, you can use
import randomrandom.sample(your_list, sample_size)
However, if you want your sublists to be contiguous (like the example you've given), you might be better off picking two random indices and slicing the list accordingly:
a = random.randint(0, len(your_list) - sample_length)
sublist = your_list[a:b+sample_length]
Post a Comment for "Selecting A Random List Element Of Length N In Python"