问题
I have a list of list L
as :
[
[1,2,3,4,5,6],
[10,20,30,40,50,60],
[11,12,113,4,15,6],
]
Inner list are of same size.
I want to choose n-random elements from every row of L
and output it as same list of list.
I tried the following code:
import random
import math
len_f=len(L)
index=[i for i in range(len_f)]
RANDOM_INDEX=random.sample(index, 5))
I am stuck at this point that how can I use random index to get output from L.
The output for "2" random elements would be:
[
[1,6],
[10,60],
[11,6],
]
If random function chose 1 and 6 as index.
回答1:
random.sample
could be leveraged. Adapt sample size k
according to your needs.
In: import random
In: [random.sample(ls, k=3) for ls in L]
Out: [[1, 2, 6], [60, 10, 30], [4, 12, 15]]
It assumes the order of the picked elements doesn't matter.
Doc for random.sample
for convenience: https://docs.python.org/3/library/random.html#random.sample
来源:https://stackoverflow.com/questions/58783205/choose-n-random-elements-from-every-row-of-list-of-list