Choose n random elements from every row of list of list

强颜欢笑 提交于 2021-02-11 12:16:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!