从数组中选择随机项

1 python

import os, glob, numpy as np

files = glob.glob('*.jpg')
indices = np.array([i for i,j in enumerate(files)])
selected_indices = np.random.choice(indices,500,replace=False)
print files[selected_indices]
Run Code Online (Sandbox Code Playgroud)

我无法将索引转换为文件.这样做的好方法是什么?

Ole*_*pin 5

这样做是正确的!

import glob
import random

files = glob.glob('*.jpg')
selected_files = random.sample(files, 500)
print(selected_files)
Run Code Online (Sandbox Code Playgroud)

这两种方法都有问题Sample larger than population.因此,如果需要,500我们可以使用min(500, len(files)).