首页 > 解决方案 > 在未知数量的列表中查找每个列表的唯一元素部分

问题描述

我正在尝试为后续问题找到有效的解决方案:

我有许多 x 列表(数量未知),每个列表都有不同但也有重叠的元素。我想找到每个列表独有的元素并分别输出。

例如,如果我有 3 个列表:

a = [1,2,3,4] 
b = [2,5,6,7]
c = [3,6,8,9]

这将导致输出(我不只是试图找到唯一的元素):

a --> [1,4]
b --> [5,7]
c --> [8,9]

假设一个列表是按顺序生成的。我正在考虑使用集合,但相信在生成每个列表时可以解决这个问题。

标签: pythonlistset

解决方案


Here is a simple solution in O(N) where N is the total number of elements.

The key idea is to count for each elements how many times it appears in all the lists. Then you can filter each list by keeping only elements that appear once.

from collections import Counter

a = [1,2,3,4]
b = [2,5,6,7]
c = [3,6,8,9]

# Count how many times each elements appear.
counter = Counter()

for l in [a,b,c]:
    counter.update(l)

print(counter)

# If an element appears only once, it is an unique element !
for l in [a,b,c]:
    print(*filter(lambda x: counter[x]==1, l))

And the output is:

Counter({2: 2, 3: 2, 6: 2, 1: 1, 4: 1, 5: 1, 7: 1, 8: 1, 9: 1})
1 4
5 7
8 9

推荐阅读