首页 > 解决方案 > 在考虑先前结果的同时运行一系列随机化

问题描述

假设我有这个文件夹:

数据

在这个文件夹中有许多文件。

假设我想这样做:

1:我想随机选择 25% 的 Data 文件并将它们存储在例如名为“75”的文件夹中。

2:那我想增加百分比。我想随机选择 50% 的 Data 文件并将它们存储在一个名为“50”的文件夹中。

现在从数据中选择的这 50%必须包括预先在1 中选择的 25%:加上另外 25%的随机数。

这是我尝试过的:

def getPercentageData(data_path, out_path, percent):
    files= os.listdir(data_path)
    files_to_keep = round(len(files) * percent)

    for file_name in random.sample(files, files_to_keep):
        shutil.copy(os.path.join(data_path, file_name), out_path) 

但这不会选择相同的文件。

标签: pythonalgorithm

解决方案


第二次采样时,您可以采样与第一次采样相同数量的文件,但从排除第一个示例中存在的文件的列表中选择它们。然后只需将第一个样本合并到您的第二个样本中。

这应该有效(这里,字母代表您的文件名):

import string
files = list(string.ascii_letters)  # placeholder list representing your file paths

import random
percent = 0.25
files_to_keep = round(len(files) * percent)

first_sample = random.sample(files, files_to_keep)

available_files = [f for f in files if f not in first_sample]
second_sample = first_sample + random.sample(available_files, files_to_keep)

print(first_sample)
# output (in my case):
# ['R', 'd', 'h', 'N', 'H', 'I', 'w', 'y', 'u', 'm', 'D', 'Y', 'r']
print(second_sample)
# output (in my case):
# ['R', 'd', 'h', 'N', 'H', 'I', 'w', 'y', 'u', 'm', 'D', 'Y', 'r', 'T', 'E', 'F', 'i', 'q', 'A', 'C', 's', 'G', 'z', 'b', 'M', 'l']

推荐阅读