I have a list of lists in python as follows:
a = [[1,1,2], [2,3,4], [5,5,5], [7,6,5], [1,5,6]] for example, How would I at random select 3 lists out of the 6?
I tried numpy's random.choice but it does not work for lists. Any suggestion?
I have a list of lists in python as follows:
a = [[1,1,2], [2,3,4], [5,5,5], [7,6,5], [1,5,6]] for example, How would I at random select 3 lists out of the 6?
I tried numpy's random.choice but it does not work for lists. Any suggestion?
numpy's random.choice doesn't work on 2-d array, so one alternative is to use lenght of the array to get the random index of 2-d array and then get the elements from that random index. see below example.
import numpy as np random_count = 3 # number of random elements to find a = [[1,1,2], [2,3,4], [5,5,5], [7,6,5], [1,5,6]] # 2-d data list alist = np.array(a) # convert 2-d data list to numpy array random_numbers = np.random.choice(len(alist), random_count) # fetch random index of 2-d array based on len for item in random_numbers: # iterate over random indexs print(alist[item]) # print random elememt through index You can use the random library like this:
a = [[1,1,2], [2,3,4], [5,5,5], [7,6,5], [1,5,6]] import random random.choices(a, k=3) >>> [[1, 5, 6], [2, 3, 4], [7, 6, 5]] You can read more about the random library at this official page https://docs.python.org/3/library/random.html.