我有一个从文件中读取项目列表的函数。如何从列表中随机选择 50 个项目以写入另一个文件?
def randomizer(input, output='random.txt'): query = open(input).read().split() out_file = open(output, 'w') random.shuffle(query) for item in query: out_file.write(item + '\n')
例如,如果总随机化文件是
random_total = ['9', '2', '3', '1', '5', '6', '8', '7', '0', '4']
我想要一个随机的 3 组,结果可能是
random = ['9', '2', '3']
如何从我随机化的列表中选择 50 个?
更好的是,我如何从原始列表中随机选择 50 个?
如果列表是随机顺序的,您可以只取前 50 个。
否则,使用
import random random.sample(the_list, 50)
random.sample帮助文本:
random.sample
sample(self, population, k) method of random.Random instance Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60)