有没有一种更简单的方法可以将列表随机拆分为子列表,而不必在python中重复元素?
我想使用预定义的比率将列表分成3个子列表(训练、验证、测试)。应随机选择子列表中的项目,不得重复。 (我的第一个列表包含拆分后要处理的文件夹中的图像名称。) 我找到了一种工作方法,但似乎很复杂。我很好奇有没有更简单的方法? 我的方法是:有没有一种更简单的方法可以将列表随机拆分为子列表,而不必在python中重复元素?,python,list,split,Python,List,Split,我想使用预定义的比率将列表分成3个子列表(训练、验证、测试)。应随机选择子列表中的项目,不得重复。 (我的第一个列表包含拆分后要处理的文件夹中的图像名称。) 我找到了一种工作方法,但似乎很复杂。我很好奇有没有更简单的方法? 我的方法是: 列出文件夹中的文件 定义子列表的必要大小 随机填写第一个子列表 从原始列表中删除已使用的项目 从剩余列表中随机填写第二个子列表 删除已使用的项以获取第三个子列表 这是我的代码: import random import os # list files i
- 列出文件夹中的文件
- 定义子列表的必要大小
- 随机填写第一个子列表
- 从原始列表中删除已使用的项目
- 从剩余列表中随机填写第二个子列表
- 删除已使用的项以获取第三个子列表
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]
我认为答案是不言自明的,所以我没有添加任何解释
import random
random.shuffle(files)
k = test_count
set1 = files[:k]
set2 = files[k:1.5k]
set3 = files[1.5k:]
我建议查看sci工具包学习库,因为它包含为您执行此操作的
train\u test\u split
函数。不过,只需使用random
库即可回答您的问题
# First shuffle the list randomly
files = os.listdir("C:/.../my_folder")
random.shuffle(files)
# Then just slice
ratio = int(len(files)/5) # 20%
test_set = files[:ratio]
val_set = files[ratio:1.5*ratio] #30%
这对meSo来说已经足够干净了,有什么问题吗?@mece1390 op想要一种更干净的方法。当他/她说我找到了一种工作方法,但很复杂时,清洁的含义是什么?什么元素使它更干净?什么因素使它复杂?你好,谢谢你的评论。我已经得到了两个答案,在我看来更简单和优雅,这是我的目标。谢谢你的回答!