【问题标题】:Is there a simpler way to split list into sublists randomly without repeating elements in python?有没有更简单的方法可以将列表随机拆分为子列表而不在 python 中重复元素?
【发布时间】:2020-12-11 15:53:38
【问题描述】:

我想使用预定义的比率将一个列表拆分为 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]

【问题讨论】:

  • 这对我来说似乎很干净
  • 那么,问题出在哪里?
  • @mece1390 操作人员想要一种更清洁的方式
  • 当他/她说我找到了一个工作方法但它很复杂时,清洁工是什么意思?什么元素使它更干净?是什么因素使它变得复杂?
  • 您好,感谢 cmets。我已经得到了 2 个在我看来更简单和优雅的答案,这是我的目标。感谢您的回答!

标签: python list split


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我建议查看 sci-kit 学习库,因为它包含 train_test_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%
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2021-03-17
      • 2023-04-06
      • 1970-01-01
      • 2010-10-07
      • 2018-12-22
      相关资源
      最近更新 更多