【问题标题】:Randomly read only 50 % of files [duplicate]随机读取仅 50% 的文件 [重复]
【发布时间】:2021-05-12 03:26:54
【问题描述】:

如何随机读取50%的文件数:

files = glob.glob("*.txt")

##suppose files are objects

for fi in files:

    #I want to implement through the for loop

    data = np.genfromtxt(fi, ...)

编辑:我想通过for循环来实现,在我的另一个问题中,文件是对象。

【问题讨论】:

  • 随机打乱文件列表并遍历前半部分元素。
  • random.sample(files, len(files) // 2)
  • 我想通过for循环来实现
  • @deceze 您应该将其发布为答案;它比我的好:)
  • 什么意思,“想通过for循环来实现”?

标签: python


【解决方案1】:

随机播放文件,然后将列表切成两半。这里,向下取整:

import random

files = glob.glob("*.txt")
random.shuffle(files)
files = files[:len(files) // 2]

for fi in files:

   data = np.genfromtxt(fi, ...)

【讨论】:

  • 我想通过for循环来实现,假设文件是​​对象
猜你喜欢
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-08
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多