首页 > 解决方案 > 有没有一种更简单的方法可以将列表随机拆分为子列表而不在 python 中重复元素?

问题描述

我想使用预定义的比率将列表拆分为 3 个子列表(训练、验证、测试)。项目应随机选择到子列表中,不重复。(我的第一个列表包含拆分后要处理的文件夹中的图像名称。)我找到了一种工作方法,但它似乎很复杂。我很好奇有没有更简单的方法来做到这一点?我的方法是:

这是我的代码:

import random
import os 

# list files in folder
files = os.listdir("C:/.../my_folder")

# define the size of the sets: ~30% validation, ~20% test, ~50% training (remaining goes to training set)
validation_count = int(0.3 * len(files))
test_count = int(0.2 * len(files))
training_count = len(files) - validation_count - test_count

# randomly choose ~20% of files to test set
test_set = random.sample(files, k = test_count)

# remove already chosen files from original list
files_wo_test_set = [f for f in files if f not in test_set]

# randomly chose ~30% of remaining files to validation set
validation_set = random.sample(files_wo_test_set, k = validation_count)

# the remaining files going into the training set
training_set = [f for f in files_wo_test_set if f not in validation_set]

标签: pythonlistsplit

解决方案


我认为答案是不言自明的,所以我没有添加任何解释。

import random
random.shuffle(files)
k = test_count
set1 = files[:k]
set2 = files[k:1.5k]
set3 = files[1.5k:]

推荐阅读