簡體   English   中英

從列表列表中刪除重復項

[英]Remove duplicates from list of lists

我有一個包含約300個列表的列表,但是其中一些是重復的,我想刪除它們。 我試過了:

cleanlist = [cleanlist.append(x) for x in oldlist if x not in cleanlist]

但它不斷拋出RuntimeError: maximum recursion depth exceeded in comparisonRuntimeError: maximum recursion depth exceeded in comparisonRuntimeError: maximum recursion depth exceeded in comparison了范圍。 我嘗試了sys.setrecursionlimit(1500)但這沒有幫助。

有什么更好的方法?

您要添加一堆東西cleanlist根據是否在cleanlist (其中尚不存在),然后保存在返回的值append()操作(這是None ),以cleanlist 它不會很好地結束。

更好的方法可能是使用老式的循環結構:

cleanlist = []
for x in oldlist:
    if x not in cleanlist:
        cleanlist.append(x)

瘋狂的解決方案。 也許有幫助:

oldlist = [[1,2,3], [1,2,3], [4,5,6], [7,8], [7,8]]
cleanlist = set(tuple(x) for x in oldlist)
print(list(cleanlist))

>>> [(7, 8), (4, 5, 6), (1, 2, 3)]

有關列表的列表,請使用以下命令:

cleanlist = [list(item) for item in set(tuple(x) for x in oldlist)]
>>> [[7, 8], [4, 5, 6], [1, 2, 3]]

暫無
暫無

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

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