且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从列表列表的每一行中选择 n 个随机元素

更新时间:2022-10-18 11:38:07

random.sample 可以利用.根据您的需要调整样本大小 k.

输入:随机导入在:[random.sample(ls, k=3) for ls in L]输出: [[1, 2, 6], [60, 10, 30], [4, 12, 15]]

它假定所选择元素的顺序无关紧要.

为方便起见,

random.sample 的文档:https://docs.python.org/3/library/random.html#random.sample

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.

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