簡體   English   中英

用於查找重復項的Python方法

[英]Python methods to find duplicates

有沒有辦法找到列表是否包含重復項。 例如:

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

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

如果將列表臨時轉換為集合,則將消除集合中的重復項。 然后,您可以比較列表和集的長度。

在代碼中,它看起來像這樣:

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

將列表轉換為一組以刪除重復項。 比較原始列表和集合的長度,以查看是否存在任何重復項。

>>> 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

檢查原始列表的長度是否大於列表中唯一“set”元素的長度。 如果是這樣,那一定是重復的

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

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

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM