我们需要一个while循环来确保我们不会重叠,你可以检查切片的长度是否符合任何其他条件,使用list comp你不能指定不同的标准:
如果您希望随机切片占总列表大小的大约5%到15%,样本大小大约为30%:
from random import choice
from numpy import arange
index = [i + 1 for i in range(365)]
choices = []
seen = set()
ar = arange(0.05,.16, .01)
ln = len(index)
sample_size = 0
while sample_size < ln * .30:
perc = choice(ar) # get random 5, 10, 15 percent slices
size = int(ln * perc)
ch = choice(index[:-size+1]) # avoid falling off the side
rn = index[ch:ch+size]
if len(rn) == size and not seen.intersection(rn):
seen.update(rn)
choices.append(rn)
sample_size += len(rn)
print(choices)