Python 检查不可损坏列表中的重复项

Python 检查不可损坏列表中的重复项,python,list,duplicates,tuples,hashable,Python,List,Duplicates,Tuples,Hashable,我有以下清单: L = [['a', 'b'], ['x'], ['a', 'b', 'c'], ['a', 'b']] 我想检查一下列表中是否有重复项 已尝试: def checkIfDuplicates_(listOfElems): ''' Check if given list contains any duplicates ''' for elem in listOfElems: if listOfElems.count(elem) > 1

我有以下清单:

L = [['a', 'b'], ['x'], ['a', 'b', 'c'], ['a', 'b']]
我想检查一下列表中是否有重复项

已尝试:

def checkIfDuplicates_(listOfElems):
    ''' Check if given list contains any duplicates '''    
    for elem in listOfElems:
        if listOfElems.count(elem) > 1:
            return True
    return False

并将每个子列表转换为元组

check_L = list(set(tuple(L) for x in L))

不工作

实际上,您与此非常接近:

check_L = list(set(tuple(L) for x in L))
有一个小错误,您使用的是
tuple(L)
,而实际需要
tuple(x)
。如果我们纠正这一点,我们将得到:

>>> list(set(tuple(x) for x in L))
[('a', 'b', 'c'), ('x',), ('a', 'b')]
要返回嵌套列表,我们可以执行以下操作:

>>> [list(y) for y in set(tuple(x) for x in L)]
[['a', 'b', 'c'], ['x'], ['a', 'b']]
希望有帮助

>>> [list(y) for y in set(tuple(x) for x in L)]
[['a', 'b', 'c'], ['x'], ['a', 'b']]