我在 Python 中有一个填充了数组的列表。
([4,1,2],[1,2,3],[4,1,2])
如何去除重复的数组?
我在 Python 中有一个填充了数组的列表。
([4,1,2],[1,2,3],[4,1,2])
如何去除重复的数组?
如果您可以将内容转换为元组/其他可哈希项,并且使用集合作为中间元素,则可以非常简单地删除重复项。
lst = ([4,1,2],[1,2,3],[4,1,2])
# convert to tuples
tupled_lst = set(map(tuple, lst))
lst = map(list, tupled_lst)
如果您需要保持顺序或不想转换为元组,可以使用集合来检查是否之前已经看到过该项,然后进行迭代,即:
seen = set()
def unique_generator(lst)
for item in lst:
tupled = tuple(item)
if tupled not in seen:
seen.add(tupled)
yield item
lst = list(unique_generator(lst))
seen = set()
lst = [item for item in lst if not(tuple(item) in seen or seen.add(tuple(item)))]
>>> from collections import OrderedDict
>>> items = ([4,1,2],[1,2,3],[4,1,2])
>>> OrderedDict((tuple(x), x) for x in items).values()
[[4, 1, 2], [1, 2, 3]]
>>> set(map(tuple, items))
set([(4, 1, 2), (1, 2, 3)])
l = ([4,1,2],[1,2,3],[4,1,2])
uniq = []
for i in l:
if not i in uniq:
uniq.append(i)
print('l=%s' % str(l))
print('uniq=%s' % str(uniq))
产生的结果为:
l=([4, 1, 2], [1, 2, 3], [4, 1, 2])
uniq=[[4, 1, 2], [1, 2, 3]]
使用集合
来跟踪已经出现的项,但是由于集合只能包含可哈希的项,因此您可能需要先将元组的项转换为某些可哈希的值(在这种情况下为元组)。
集合提供O(1)
的查找,因此总体复杂度将是O(N)
此生成器函数将保留顺序:
def solve(lis):
seen = set()
for x in lis:
if tuple(x) not in seen:
yield x
seen.add(tuple(x))
>>> tuple( solve(([4,1,2],[1,2,3],[4,1,2])) )
([4, 1, 2], [1, 2, 3])
set()
:>>> lis = ([4,1,2],[1,2,3],[4,1,2]) # this contains mutable/unhashable items
>>> set( tuple(x) for x in lis) # apply tuple() to each item, to make them hashable
set([(4, 1, 2), (1, 2, 3)]) # sets don't preserve order
>>> lis = [1, 2, 2, 4, 1] #list with immutable/hashable items
>>> set(lis)
set([1, 2, 4])