繁体   English   中英

有没有办法在保持原始顺序的同时删除列表中的重复项?

[英]Is there a way to remove duplicates in a list while keeping original order?

有没有办法保留列表中元素的原始顺序? 使用下面的代码,我将其作为输出

值: [1, 3, 0, 1, 4, 1, 1, 2, 2, 5, 4, 3, 1, 3, 3, 4, 2, 4, 3, 1, 3, 0, 3, 0, 0]

清洁: [5, 2, 4, 1, 3, 0]

我需要[1, 2, 0, 4, 5, 3]作为“干净”列表

def remove_duplicates(lst)
 i = len(lst)
 while i>0:
  while values.count(values[i]>1:
   values.remove(values[i])
   i-=1
  i-=1
 return

使用 for 循环和新的列表输出解决这个问题似乎很简单,但我需要使用 while 循环并坚持只使用一个列表。

def remove_duplicates(lst):
 new =[]
 for x in lst:
  if x not in lst:
   new.append(x)
 return new
def remove_duplicates(lst):
    i = 0
    while i < len(lst):
        j = i + 1
        while j < len(lst):  # check for duplicates of lst[i] and remove them
            if lst[i] == lst[j]:
                del lst[j]
            else:
                j += 1  # only increment second idx if the item is not removed!
        i += 1
    return

并测试它:

>>> lst = [1, 3, 0, 1, 4, 1, 1, 2, 2, 5, 4, 3, 1, 3, 3, 4, 2, 4, 3, 1, 3, 0, 3, 0, 0]
>>> remove_duplicates(lst)
>>> lst
[1, 3, 0, 4, 2, 5]

您也可以使用set而不是第二个 while 循环来实现它(这显然更快,但我不确定是否允许!):

def remove_duplicates(lst):
    i = 0
    found = set()
    while i < len(lst):
        if lst[i] in found:
            del lst[i]
        else:
            found.add(lst[i])
            i += 1
    return

可以在list.remove的文档中找到有关为什么您的方法不起作用的快速说明:

list.remove(x)

从列表中删除值为 x 的第一项。 如果没有这样的项目,这是一个错误。

但是您想删除除第一个之外的所有出现!

暂无
暂无

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

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