到目前为止,我已经知道了如何导入文件、创建新文件和随机化列表
我无法从列表中随机选择50项写入文件
def randomizer(input,output1='random_1.txt',output2='random_2.txt',output3='random_3.txt',output4='random_total.txt'):
#Input file
query=open(input,'r').read().split()
dir,file=os.path.split(input)
temp1 = os.path.join(dir,output1)
temp2 = os.path.join(dir,output2)
temp3 = os.path.join(dir,output3)
temp4 = os.path.join(dir,output4)
out_file4=open(temp4,'w')
random.shuffle(query)
for item in query:
out_file4.write(item+'\n')
所以如果整个随机化文件是
example:
random_total = ['9','2','3','1','5','6','8','7','0','4']
我想要3个文件(out|file1 | 2 | 3),第一个随机集为3,第二个随机集为3,第三个随机集为3(在本例中,但我要创建的文件应该有50个)
random_1 = ['9','2','3']
random_2 = ['1','5','6']
random_3 = ['8','7','0']
因此,最后的“4”将不包括在内,这很好
如何从我随机化的列表中选择50
更好的是,我怎么能从原始列表中随机选择50个呢?
我认为
random.choice()
是一个更好的选择该函数返回从列表中随机选择的3个值的数组
如果列表是随机排列的,你可以只取前50个
否则,请使用
random.sample
帮助文本:选择随机项目的一个简单方法是先洗牌,然后切片
相关问题 更多 >
编程相关推荐