Python 从数组中选择随机项
我无法将索引转换为文件。做这件事的好方法是什么?问题是Python 从数组中选择随机项,python,Python,我无法将索引转换为文件。做这件事的好方法是什么?问题是glob.glob('*.jpg')返回一个列表,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
glob.glob('*.jpg')
返回一个列表,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]
然而,有一种更好的方法请参见问题是
glob.glob('*.jpg')
返回一个列表,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]
然而,有一种更好的方法请参见以正确的方式操作!
当样本大于总体时,这两种方法都有问题。因此,如果需要,我们可以使用min(500,len(文件))
而不是500
。用正确的方法!
当样本大于总体时,这两种方法都有问题。因此,如果需要,我们可以使用min(500,len(文件))
来代替500
import glob
import random
files = glob.glob('*.jpg')
selected_files = random.sample(files, 500)
print(selected_files)