用于查找重复项的Python方法

时间:2012-06-28 17:24:01

标签: python

有没有办法查找列表是否包含重复项。例如:

list1 = [1,2,3,4,5]
list2 = [1,1,2,3,4,5]

list1.*method* = False # no duplicates
list2.*method* = True # contains duplicates

4 个答案:

答案 0 :(得分:14)

如果您暂时将列表转换为集合,则会消除集合中的重复项。然后,您可以比较列表的长度和设置。

在代码中,它看起来像这样:

list1 = [...]
tmpSet = set(list1)
haveDuplicates = len(list1) != len(tmpSet)

答案 1 :(得分:2)

将列表转换为一组以删除重复项。比较原始列表和集合的长度,以查看是否存在重复项。

>>> list1 = [1,2,3,4,5]
>>> list2 = [1,1,2,3,4,5]
>>> len(list1) == len(set(list1))
True # no duplicates
>>> len(list2) == len(set(list2))
False # duplicates

答案 2 :(得分:2)

检查原始列表的长度是否大于列表中唯一“set”元素的长度。如果是这样,那一定是重复的

list1 = [1,2,3,4,5]
list2 = [1,1,2,3,4,5]

if len(list1) != len(set(list1)):
    #duplicates

答案 3 :(得分:0)

set()方法仅适用于可散列对象,因此为了完整性,您只需使用普通迭代即可:

import itertools

def has_duplicates(iterable):
    """
    >>> has_duplicates([1,2,3])
    False
    >>> has_duplicates([1, 2, 1])
    True
    >>> has_duplicates([[1,1], [3,2], [4,3]])
    False
    >>> has_duplicates([[1,1], [3,2], [4,3], [4,3]])
    True
    """
    return any(x == y for x, y in itertools.combinations(iterable, 2))