[英]"IndexError: list index out of range" error in python
我是python的新手。 运行我的文件后出现错误。 文件"C:Users/USER/PycharmProjects/Research/trainer1file (1).py"
, line 42, in process iteratorclasses = iter(sorted(os.walk(data))[1])
IndexError: list index out of range
def process(data, mode, batch_size):
images, labels = list(), list()
if mode == 'file':
with open(data) as f:
data = f.read().splitlines()
for d in data:
images.append(d.split(' ')[0])
labels.append(int(d.split(' ')[1]))
elif mode == 'folder':
label = 0
iteratorclasses = iter(sorted(os.walk(data))[1])
classes = next(iteratorclasses)
for c in classes:
c_dir = os.path.join(data, c)
iteratorwalk = iter(os.walk(c_dir))
walk = next(iteratorwalk)
# Add each image to the training set
for sample in walk[2]:
# Only keeps jpeg images
if sample.endswith('.jpg') or sample.endswith('.jpeg') or sample.endswith('.JPG'):
images.append(os.path.join(c_dir, sample))
labels.append(label)
label += 1
else:
raise Exception("Unknown mode.")
images = tf.convert_to_tensor(images, dtype=tf.string)
labels = tf.convert_to_tensor(labels, dtype=tf.int32)
image, label = tf.train.slice_input_producer([images, labels],
shuffle=True)
x, y = tf.train.batch([image, label], batch_size=batch_size,
capacity=batch_size * 8,
num_threads=4)
return x, y
您尝试浏览的目录中可能没有任何内容,这就是索引超出范围的原因。
IndexError: list index out of range
立即是一个警告信号。 只需阅读错误! 它说l[i]
其中l
是列表, i
是索引不存在,因为l
没有i
或更多索引。
例如,假设我在 Python 中运行
l = [1,2,3]
l[1]
它会返回什么? 2
,当然。
l[10]
呢?
没有第 10 个索引,因此它将返回IndexError: list index out of range
。
这次我会让你离开,但你不能给我们代码和错误,并期望我们为你解决它。
sorted()
在您的情况下,将返回一个包含一个元素的列表,即一个包含根目录、目录列表和文件列表的集合。 因此出现错误(因为您要访问索引 1,所以要访问不存在的第二个元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.