我编写了以下代码来删除列表中的重复项:
def remove_duplicates(listy):
new_listy = []
for i in range(len(listy)):
a = listy.pop(i)
while a in listy:
listy = listy.remove(a)
else: new_listy.append(a)
return new_listy
运行代码时出现以下错误:
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
remove_duplicates([1,1,2,2])
File "C:\Python27\MIT_4.py", line 4, in remove_duplicates
a = listy.pop(i)
AttributeError: 'NoneType' object has no attribute 'pop.
导致此错误的原因是什么?如何正确解决这个问题?
答案 0 :(得分:1)
要删除重复项,如果排序不重要,您可以使用set
功能。但是如果你的目的是学习python,那么知道你的代码有什么问题是很重要的。
这非常简单:for i in range(len(listy)):
请改为使用for item in listy:
以这种方式使用a = listy.pop(i)
会导致问题,因为在循环列表中元素被删除。 pop()
执行时,循环开始时的元素将不再可用。
删除功能不返回列表!所以这是错误的:listy = listy.remove(a)
无论如何都无需从列表中删除,因为您正在制作新列表。如果您想更新listy,请将函数的返回值分配给listy。
删除重复项并返回保留原始订单的新列表的一种方法:
def remove_duplicates(listy):
new_listy = []
for item in listy:
if item not in new_listy:
new_listy.append(item)
return new_listy
答案 1 :(得分:0)
删除重复项,您可以使用set function
lst = [1,1,1,2,3,4]
print list(set(lst))
输出
[1, 2, 3, 4]
答案 2 :(得分:0)
试试这个。我已经重新安排了你的功能,它会给你想要的结果
list1 = [1,1,2,2,3]
def remove_duplicates(listy):
new_listy = []
for i in listy:
if i not in new_listy:
new_listy.append(i)
return new_listy
print remove_duplicates(list1)
Output: [1,2,3]
答案 3 :(得分:0)
lista.remove不会创建新列表,因此您无法像这样分配结果:
listy = listy.remove(a)
然后listy为None,并且在尝试在None而不是列表上调用pop()时会出错。
您的代码中还有其他错误。我建议阅读这些命令的文档,以便更好地理解它们。