python生成1到100之间随机数
python⽣成20个随机数列表,Python:如何创建由随机数组成
的,长度增加的列表列表?...
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.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。