python - 在考虑先前结果的同时运行一系列随机化
问题描述
假设我有这个文件夹:
数据
在这个文件夹中有许多文件。
假设我想这样做:
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)
但这不会选择相同的文件。
解决方案
第二次采样时,您可以采样与第一次采样相同数量的文件,但从排除第一个示例中存在的文件的列表中选择它们。然后只需将第一个样本合并到您的第二个样本中。
这应该有效(这里,字母代表您的文件名):
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']
推荐阅读
- typescript - 为什么推断类型可以转换为索引集合,而看似相同的显式类型却不能?
- javascript - 从私钥生成比特币公共地址的尝试失败
- css - 通过 css 更改调整大小的属性
- twilio - Gather 动词不适用于会议中的第一个参与者,仅适用于最后一个连接的参与者
- json - 当默认时间戳格式设置为其他内容时,如何在 Spring Boot 控制器请求正文中传递日期 yyyy-mm-dd
- python - scrapy-splash 不返回splash处理的html
- pega - 如何从字段中保存数据
- node.js - 使用 Crypto 的 AES 加密和使用 CryptoJS 的解密返回空字符串
- css - 我在 HTML 5 和 CSS 中的标题横幅不起作用
- javascript - js代码在开始时对图像进行错误旋转