Skip to main content
 首页 » 编程设计

python之从数组中选择随机项

2025年05月04日15think

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] 

我无法将索引转换为文件。有什么好的方法吗?

请您参考如下方法:

以正确的方式去做!

import glob 
import random 
 
files = glob.glob('*.jpg') 
selected_files = random.sample(files, 500) 
print(selected_files) 

当 Sample large than population 时,这两种方法都有问题。因此,如果需要,我们可以使用 min(500, len(files)) 而不是 500。