Python:如何创建由随机数组成的,长度不断增加的列表列表? [英] Python: how to create a list of lists with increasing length, made of random numbers?
问题描述
说我有200个称为masterlist
的正,唯一,随机整数的列表.
container
的10个列表的列表,这样:l1
有两个来自masterlist
的随机数,不包括重复; l2
有4个元素,l3
有6个元素,依此类推.
我知道我可以这样创建我的container
列表:
comb=[[] for i in range(10)]
,然后我可以使用random.choice()
从列表中选择一个随机值.
嵌套这10个列表的填充过程的最好的Python方法是什么,以便我创建一个列表,附加正确数量的值以检查没有重复,然后继续下一个?
编辑
这是我的尝试:
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))
这有什么问题?
这应该可以解决问题:
import random
masterlist = [i for i in range(200)] # For example
container = [
random.sample(masterlist, l)
for l in range(2, 21, 2)
]
容器由列表理解组成,使用range()
调用将变量l
设置为2、4、6 ... 18、20.在理解的每个循环"中,内置的random.sample()
调用会执行您要进行的无替换采样.
Say I have a list of 200 positive, unique, random integers called masterlist
.
I want to generate a list of 10 lists called container
so that: l1
has 2 random numbers coming from masterlist
, repetitions excluded; l2
has 4 elements, l3
has 6 elements, and so forth.
I know I can create my container
list like this:
comb=[[] for i in range(10)]
and that I can select a random value from a list using 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?
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. Within each 'loop' of the comprehension, the built in random.sample()
call does the sampling-without-replacement that you're after.
这篇关于Python:如何创建由随机数组成的,长度不断增加的列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!