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_Python 3.x - Fatal编程技术网

Python 列表索引超出范围,不确定原因?

Python 列表索引超出范围,不确定原因?,python,list,python-3.x,Python,List,Python 3.x,我用这段代码得到一个“列表索引超出范围”,但当我将new\u list初始化为空列表时,我没有。有人能解释一下原因吗? 此函数获取数字列表并“删除”重复项 def remove_duplicates(numbers): new_list = [numbers[0]] for x in numbers: if x not in new_list: new_list.append(x) return new_list 当数字列表为/可

我用这段代码得到一个“列表索引超出范围”,但当我将
new\u list
初始化为空列表时,我没有。有人能解释一下原因吗? 此函数获取数字列表并“删除”重复项

def remove_duplicates(numbers):
    new_list = [numbers[0]]
    for x in numbers:
        if x not in new_list:
            new_list.append(x)
    return new_list

当数字列表为/可能为空时,无法获取编号[0]。
更好的解决方案是使用
数字[0],如果len(数字)或None
这确实是一个XY问题。如果要从列表中删除重复项,只需将其转换为集合:

unique_values = list(set(numbers))

编号中有什么?你希望数字[0]是什么?
数字是一个空列表。
数字应该是一个整数列表,@doctorlove,如果它是空的呢?请给出一个你调用它的代码的例子,它会导致错误。我在codeacademy课程中写了这个代码,看起来他们用多个输入测试你的代码,但没有确切告诉你。我想我现在明白了,谢谢@DoctorLove事实上,您不需要将列表初始化为
数字[0]
,只要将其初始化为
[]
,就足够了。是的,我只是好奇为什么@lejlot会有不同。我想我现在明白了,谢谢你