[英]Python: how to create a list of lists with increasing length, made of random numbers?
Say I have a list of 200 positive, unique, random integers called masterlist
. 假设我有一个200个称为
masterlist
正,唯一,随机整数的masterlist
。
I want to generate a list of 10 lists called container
so that: l1
has 2 random numbers coming from masterlist
, repetitions excluded; 我想生成一个称为
container
的10个列表的列表,以便: l1
有2个来自masterlist
随机数,排除了重复项; l2
has 4 elements, l3
has 6 elements, and so forth. l2
有4个元素, l3
有6个元素,依此类推。
I know I can create my container
list like this: 我知道我可以这样创建我的
container
列表:
comb=[[] for i in range(10)]
and that I can select a random value from a list using random.choice()
. 而且我可以使用
random.choice()
从列表中选择一个随机值。
What is the best Pythonic way to nest the populating process of these 10 lists, so that I create one list, append the correct number of values checking that there are no repetitions, and proceed on to the next? 嵌套这10个列表的填充过程的最佳Pythonic方法是什么,以便我创建一个列表,追加正确数量的值以检查是否存在重复项,然后继续进行下一个?
EDIT 编辑
This is my attempt: 这是我的尝试:
comb=[[] for i in range(10)]
for j in range(1,11):
for k in range(0,2*j):
comb[j][k].append(random.choice(masterlist))
What is wrong with this? 这有什么问题?
This should do the trick: 这应该可以解决问题:
import random
masterlist = [i for i in range(200)] # For example
container = [
random.sample(masterlist, l)
for l in range(2, 21, 2)
]
The container is made up of a list comprehension, setting the variable l
to 2, 4, 6 ... 18, 20 using the range()
call. 容器由列表推导组成,使用
range()
调用将变量l
设置为2、4、6 ... 18、20。 Within each 'loop' of the comprehension, the built in random.sample()
call does the sampling-without-replacement that you're after. 在理解的每个“循环”中,内置的
random.sample()
调用都会执行您要进行的无替换采样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.