Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python错误:列表索引超出范围_Python_List - Fatal编程技术网

Python错误:列表索引超出范围

Python错误:列表索引超出范围,python,list,Python,List,我一直在获取超出范围的错误列表索引。我不确定我做错了什么 我的代码: from scanner import * def small(array): smallest=array[0] for i in range(len(array)): if (array[i]<smallest): smallest=array[i] return smallest def main(): s=Scanner("data.tx

我一直在获取超出范围的错误列表索引。我不确定我做错了什么

我的代码:

from scanner import *

def small(array):
    smallest=array[0]
    for i in range(len(array)):
        if (array[i]<smallest):
            smallest=array[i]
    return smallest

def main():
    s=Scanner("data.txt")
    array=[]
    i=s.readint()
    while i!="":
        array.append(i)
        i=s.readint()
    s.close()
    print("The smallest is", small(array))

main()
我得到的回溯:

Traceback (most recent call last):
  File "file.py", line 21, in <module>
    main()
  File "file.py", line 20, in main
    print("The smallest is", small(array))
  File "file.py", line 5, in small
    smallest=array[0]
IndexError: list index out of range
数组为空。当列表为空时,不存在数组[0]

您可以测试此edgecase,也许:

def small(array):
    if not array:
        return None

您传递的数组可能为空。例如,如果输入文件中有空行或空数据。

假设第一次调用.readint返回,那么在while循环之后,数组仍然是[],因此数组[0]导致索引器。

请向我们展示完整的回溯,好吗?请发布包含完整回溯的帖子。您可能正在向小函数传递一个空数组。。考虑为此添加错误处理!回溯最近的调用最后一次:File File.py,第21行,在main File.py,第20行,在main print中最小的是smallarray File.py,第5行,在small minimable=array[0]索引器中错误:列出索引range@user3022573:下次,您的问题将添加回溯。我已经为您添加了它。