简体   繁体   English

从嵌套列表中删除重复项

[英]Remove duplicates from a nested list

I have a list 我有一个清单

A = [['1'],['1','2'],['1','2','3','1','2'],['3','3','3']]

and I want to make my list to 我想列出我的清单

A = [['1'],['1','2'],['1','2','3'],['3']]

ie I want to remove duplicate elements within the elements in a list .. 即我想删除列表中的元素内的重复元素。

One-liner (If order doesn't matter) : 一线(如果顺序无关紧要):

A = [['1'],['1','2'],['1','2','3','1','2'],['3','3','3']]
A = [list(set(a)) for a in A]
print(A) # => [['1'], ['2', '1'], ['3', '2', '1'], ['3']]

One-liner (If order matters) : 单线(如果需要订购):

A = [['1'],['1','2'],['1','2','3','1','2'],['3','3','3']]
A = [sorted(set(a), key=a.index) for a in A]
print(A) # => [['1'], ['1', '2'], ['1', '2', '3'], ['3']]

A functional version, with functools : 功能版本,带有functools

>>> import functools
>>> A = [['1'],['1','2'],['1','2','3','1','2'],['3','3','3']]
>>> print ([functools.reduce(lambda result,x:result if x in result else result+[x], xs, []) for xs in A])
[['1'], ['1', '2'], ['1', '2', '3'], ['3']]

The lambda function adds an element to the result list only if that element is not present in the list. 仅当列表中不存在该元素时,lambda函数才会将其添加到result列表中。 Not very efficient, but keeps the order of elements. 效率不高,但是保持元素顺序。

Also note that with Python 2, you don't need to import functools : reduce is a builtin function. 另请注意,在Python 2中,您无需导入functoolsreduce是一个内置函数。

You can use a generator: 您可以使用生成器:

def remove_dups(l):
   for a in l:
      new_l = []
      for b in a:
          if b not in new_l:
             new_l.append(b)
      yield new_l

A = [['1'],['1','2'],['1','2','3','1','2'],['3','3','3']]
print(list(remove_dups(A)))

Output: 输出:

[['1'], ['1', '2'], ['1', '2', '3'], ['3']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM