[英]Remove duplicates from list of lists
I have a list containing ~300 lists, however some of them are duplicates and I would like to remove them. 我有一个包含约300个列表的列表,但是其中一些是重复的,我想删除它们。 I've tried:
我试过了:
cleanlist = [cleanlist.append(x) for x in oldlist if x not in cleanlist]
but it keeps throwing RuntimeError: maximum recursion depth exceeded in comparison
at me. 但它不断抛出
RuntimeError: maximum recursion depth exceeded in comparison
我RuntimeError: maximum recursion depth exceeded in comparison
, RuntimeError: maximum recursion depth exceeded in comparison
了范围。 I tried sys.setrecursionlimit(1500)
but that didn't help. 我尝试了
sys.setrecursionlimit(1500)
但这没有帮助。
What's a better way to do this? 有什么更好的方法?
You're adding a bunch of stuff to cleanlist
based on whether it's in cleanlist
(which doesn't exist yet), and then saving the value returned from the append()
operation (which is None
) to cleanlist
. 您要添加一堆东西
cleanlist
根据是否在cleanlist
(其中尚不存在),然后保存在返回的值append()
操作(这是None
),以cleanlist
。 It will not end well. 它不会很好地结束。
A better way to do this is probably with an old-fashioned loop construct: 更好的方法可能是使用老式的循环结构:
cleanlist = []
for x in oldlist:
if x not in cleanlist:
cleanlist.append(x)
A crazy solution. 疯狂的解决方案。 Maybe It helps:
也许有帮助:
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)]
For a list of lists, use this: 有关列表的列表,请使用以下命令:
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.