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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值