简体   繁体   English

python中的“IndexError:列表索引超出范围”错误

[英]"IndexError: list index out of range" error in python

I am new to python.我是python的新手。 I get an error after running my file.运行我的文件后出现错误。 File "C:Users/USER/PycharmProjects/Research/trainer1file (1).py" , line 42, in process iteratorclasses = iter(sorted(os.walk(data))[1])文件"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

is immediately a warning sign.立即是一个警告信号。 Just read the error!只需阅读错误! It says that the l[i] where l is the list and i is the index does not exist since l does not have i or more indices.它说l[i]其中l是列表, i是索引不存在,因为l没有i或更多索引。

eg Let's say I run in Python例如,假设我在 Python 中运行

l = [1,2,3]
l[1]

What will it return?它会返回什么? 2 , of course. 2 ,当然。
What about l[10] ? l[10]呢?

There is no 10th index so it'll return IndexError: list index out of range .没有第 10 个索引,因此它将返回IndexError: list index out of range

I'll let you away this time, but you just can't give us code and the error and expect us to solve it for you.这次我会让你离开,但你不能给我们代码和错误,并期望我们为你解决它。

sorted() in your case, will return a list with one element, namely a set that contains root dir, list of directories and list of files. sorted()在您的情况下,将返回一个包含一个元素的列表,即一个包含根目录、目录列表和文件列表的集合。 therefore the error (because you want to access index 1, so the second element, which is not existing).因此出现错误(因为您要访问索引 1,所以要访问不存在的第二个元素)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM