如何从嵌套列表中删除重复的值?



以下是我的清单:

lists=[[2], [3], [4, 5, 6], [7], [8], [9], [9, 10, 11], [10]]

我想删除与其他元素重复的值。

列表中[9][10]都在[9,10,11]

I want[9,10,11]保留,但删除单个[9][10]

谁能告诉我怎么做?

我希望可以列表:

lists=[[2], [3], [4, 5, 6], [7], [8], [9, 10, 11]]

这是我的方法。

  1. 我们将使用一组(称之为a)来存储所有的元素出现在列表的长度超过1。
  2. 我们将浏览单个元素列表。如果它出现在集合中,我们不应该添加它。

下面是一个实现(希望它易于理解和阅读,以及完整的注释):

lists = [[2], [3], [4, 5, 6], [7], [8], [9], [9, 10, 11], [10]]
ans = []
a = set() 
for i in lists:
if len(i) > 1: #if this is a list with more than 1 element
for j in i: #go through its elements
a.add(j) #put it in the set, so we know what to ignore later
for i in lists:
if len(i) > 1:
ans.append(i) #if there's more than 1 element, we should add it to the final answer
else:
if i[0] not in a:
ans.append(i) #append if it does not appear in the set
lists = ans #copy the answer list to the original (optional step)
print(lists) 

这给出了期望的输出:

[[2], [3], [4, 5, 6], [7], [8], [9, 10, 11]]

当然,如果您不关心可读性,您可以使用一行代码:

lists = list(filter(lambda i: len(i) > 1 or not (any(i[0] in sb for sb in list(filter(lambda i: len(i) > 1, lists)))), lists))

这将给出相同的正确输出。