从列表列表的每一行中选择 n 个随机元素 [英] Choose n random elements from every row of list of list
问题描述
我有一个列表 L
为:
<代码> [[1,2,3,4,5,6],[10,20,30,40,50,60],[11,12,113,4,15,6],]
内部列表大小相同.我想从 L
的每一行中选择 n 个随机元素并将其输出为相同的列表列表.
我尝试了以下代码:
随机导入导入数学len_f=len(L)index=[i for i in range(len_f)]RANDOM_INDEX=random.sample(index, 5))
此时我被困在如何使用随机索引从 L 获取输出的问题上.
2"个随机元素的输出将是:
<预><代码> [[1,6],[10,60],[11,6],]如果随机函数选择 1 和 6 作为索引.
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
这篇关于从列表列表的每一行中选择 n 个随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!