I want to remove all duplicates list from a list of list.
我想从列表列表中删除所有重复列表。
So I have a list of lists like this.
所以我有一个像这样的列表。
a = [[1,2],[1,2],[3,4,5],[3,4,5],[3,4,5]]
I want to have:
我希望有:
b = [[1,2],[3,4,5]]
I don't know how to do.
我不知道该怎么做。
Thank you
2 个解决方案
#1
51
You could use a set:
你可以使用一套:
b_set = set(map(tuple,a)) #need to convert the inner lists to tuples so they are hashable
b = map(list,b_set) #Now convert tuples back into lists (maybe unnecessary?)
Or, if you prefer list comprehensions/generators:
或者,如果您更喜欢列表推导/生成器:
b_set = set(tuple(x) for x in a)
b = [ list(x) for x in b_set ]
Finally, if order is important, you can always sort b:
最后,如果订单很重要,您可以随时排序b:
b.sort(key = lambda x: a.index(x) )
#2
10
See mgilson's answer if the order of the lists is not important. If you want to retain the order, do something like:
如果列表的顺序不重要,请参阅mgilson的答案。如果您想保留订单,请执行以下操作:
b = list()
for sublist in a:
if sublist not in b:
b.append(sublist)
This will keep the order in the original list. However, it is slower and more verbose than using sets.
这将使订单保持在原始列表中。但是,它比使用集更慢,更冗长。
#1
51
You could use a set:
你可以使用一套:
b_set = set(map(tuple,a)) #need to convert the inner lists to tuples so they are hashable
b = map(list,b_set) #Now convert tuples back into lists (maybe unnecessary?)
Or, if you prefer list comprehensions/generators:
或者,如果您更喜欢列表推导/生成器:
b_set = set(tuple(x) for x in a)
b = [ list(x) for x in b_set ]
Finally, if order is important, you can always sort b:
最后,如果订单很重要,您可以随时排序b:
b.sort(key = lambda x: a.index(x) )
#2
10
See mgilson's answer if the order of the lists is not important. If you want to retain the order, do something like:
如果列表的顺序不重要,请参阅mgilson的答案。如果您想保留订单,请执行以下操作:
b = list()
for sublist in a:
if sublist not in b:
b.append(sublist)
This will keep the order in the original list. However, it is slower and more verbose than using sets.
这将使订单保持在原始列表中。但是,它比使用集更慢,更冗长。