我编写了以下 python 函数来从给定列表中删除重复项:
def remove_dup(mylist):
for item in mylist:
while mylist.count(item) > 1:
mylist.remove(item)
return mylist
它似乎可以处理整数列表,但是只要我包含一个字符串,它就不会按预期执行。例如:
ml=[1, 1, 'b', 1, 1, 'a', 45, 2, 2, 'b', 2, 2, 3, 'a', 3, 3, 45]
remove_dup(ml)
['b', 1, 'b', 2, 'a', 3, 45]
所以我在列表中得到了两次“b”。我是 Python 新手,但为什么会这样?
答案 0 :(得分:0)
您的代码的问题在于您在迭代时修改了 list
。您可以通过迭代列表副本来修复您的代码。
def remove_dup(mylist):
for item in list(mylist):
# ^ `list(my_list)` will return a new list
while mylist.count(item) > 1:
mylist.remove(item)
return mylist
样品运行:
>>> ml=[1, 1, 'b', 1, 1, 'a', 45, 2, 2, 'b', 2, 2, 3, 'a', 3, 3, 45]
>>> remove_dup(ml)
[1, 'b', 2, 'a', 3, 45]
您还可以参考 Removing duplicates in the lists 的回答来检查实现这一目标的更好替代方案。