# 从列表中获取随机样品，同时保持项目的顺序？

``mylist = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ,9 , 10 ]` `

` `randomList = getRandom(mylist,4) # randomList = [ 3 , 6 ,7 , 9 ] randomList = getRandom(mylist,4) # randomList = [ 1 , 2 , 4 , 8 ]` `

` `rand_smpl = [ mylist[i] for i in sorted(random.sample(xrange(len(mylist)), 4)) ]` `

` `random.sample(xrange(len(mylist)), sample_size)` `

## 简单的代码O（N + K * log（K））方式

` `indices = random.sample(range(len(myList)), K) [myList[i] for i in sorted(indices)]` `

` `[x[1] for x in sorted(random.sample(enumerate(myList),K))]` `

## 优化的O（N）时间，O（1） – 辅助空间的方式

` `from __future__ import division def orderedSampleWithoutReplacement(seq, k): if not 0<=k<=len(seq): raise ValueError('Required that 0 <= sample_size <= population_size') numbersPicked = 0 for i,number in enumerate(seq): prob = (k-numbersPicked)/(len(seq)-i) if random.random() < prob: yield number numbersPicked += 1` `

` `>>> Counter( tuple(orderedSampleWithoutReplacement([0,1,2,3], 2)) for _ in range(10**9) ) Counter({ (0, 3): 166680161, (1, 2): 166672608, (0, 2): 166669915, (2, 3): 166667390, (1, 3): 166660630, (0, 1): 166649296 })` `

（这也是用户tegan在注释中的一个有用的注释：如果这是python2，那么像往常一样，如果你真的关心额外的空间，你将会想要使用xrange。）

` `from __future__ import division import random def orderedSampleWithoutReplacement(seq, sampleSize): totalElems = len(seq) if not 0<=sampleSize<=totalElems: raise ValueError('Required that 0 <= sample_size <= population_size') picksRemaining = sampleSize for elemsSeen,element in enumerate(seq): elemsRemaining = totalElems - elemsSeen prob = picksRemaining/elemsRemaining if random.random() < prob: yield element picksRemaining -= 1 from collections import Counter Counter( tuple(orderedSampleWithoutReplacement([0,1,2,3], 2)) for _ in range(10**5)` `

` `myRange = range(0,len(mylist)) shuffle(myRange) coupons = [ bestCoupons[i] for i in sorted(myRange[:4]) ]` `

` `randIndex = random.sample(range(len(mylist)), sample_size) randIndex.sort() rand = [mylist[i] for i in randIndex]` `

random.sample实现它。

` `>>> random.sample([1, 2, 3, 4, 5], 3) # Three samples without replacement [4, 1, 5]` `