我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?


当前回答

def remove_duplicates(A):
   [A.pop(count) for count,elem in enumerate(A) if A.count(elem)!=1]
   return A

用于删除重复项的列表推导

其他回答

创建一个新的列表,保持L中重复元素的第一个元素的顺序:

newlist = [ii for n,ii in enumerate(L) if ii not in L[:n]]

例如:如果L =[1,2,2,3,4,2,4,3,5],则newlist将为[1,2,3,4,5]

这将在添加之前检查之前没有出现在列表中的每个新元素。 它也不需要进口。

有许多其他的答案提出了不同的方法,但它们都是批处理操作,其中一些会抛弃原始的顺序。这可能是可以的,这取决于你需要什么,但如果你想在每个值的第一个实例的顺序上迭代值,并且你想要立即删除重复的值而不是一次性删除,你可以使用这个生成器:

def uniqify(iterable):
    seen = set()
    for item in iterable:
        if item not in seen:
            seen.add(item)
            yield item

这将返回一个生成器/迭代器,因此您可以在任何可以使用迭代器的地方使用它。

for unique_item in uniqify([1, 2, 3, 4, 3, 2, 4, 5, 6, 7, 6, 8, 8]):
    print(unique_item, end=' ')

print()

输出:

1 2 3 4 5 6 7 8

如果你想要一个列表,你可以这样做:

unique_list = list(uniqify([1, 2, 3, 4, 3, 2, 4, 5, 6, 7, 6, 8, 8]))

print(unique_list)

输出:

[1, 2, 3, 4, 5, 6, 7, 8]

在Python 2.7中,从可迭代对象中删除重复项同时保持其原始顺序的新方法是:

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

在Python 3.5中,OrderedDict有一个C实现。我的计时显示,这是Python 3.5的各种方法中最快和最短的。

在Python 3.6中,常规字典变得既有序又紧凑。(此特性适用于CPython和PyPy,但在其他实现中可能不存在)。这为我们提供了一种新的最快的方法,在保持秩序的同时减少数据:

>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

在Python 3.7中,常规字典保证在所有实现中都是有序的。所以,最短最快的解决方案是:

>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

如果列表是有序的,则可以使用以下方法对其进行迭代,跳过重复的值。这对于处理内存消耗低的大列表特别有用,可以避免构建dict或set的成本:

def uniq(iterator):
    prev = None
    for item in iterator:
        if item != prev:
            prev = item
            yield item

然后:

for item in uniq([1, 1, 3, 5, 5, 6]):
    print(item, end=' ')

输出将是:1 3 5 6

要返回一个列表对象,你可以这样做:

>>> print(list(uniq([1, 1, 3, 5, 5, 6])))
[1, 3, 5, 6]

要删除重复的,将其设置为SET,然后再次将其设置为LIST,并打印/使用它。 一个集合保证有唯一的元素。例如:

a = [1,2,3,4,5,9,11,15]
b = [4,5,6,7,8]
c=a+b
print c
print list(set(c)) #one line for getting unique elements of c

输出将如下所示(在python 2.7中检查)

[1, 2, 3, 4, 5, 9, 11, 15, 4, 5, 6, 7, 8]  #simple list addition with duplicates
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15] #duplicates removed!!