python - 在未知数量的列表中查找每个列表的唯一元素部分
问题描述
我正在尝试为后续问题找到有效的解决方案:
我有许多 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]
假设一个列表是按顺序生成的。我正在考虑使用集合,但相信在生成每个列表时可以解决这个问题。
解决方案
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
推荐阅读
- docker - Why does Docker require PATH when building from custom Dockerfile in another directory?
- java - 这是由方法 System.gc() 引起的 CMS gc 吗?
- java - 为什么我在向 Spring 3 控制器发出 POST 请求时收到 SRVE0295E?
- java - MapStruct : Mapping Collections objects based on it's type's properties
- excel - 处理 Excel 文档中的无效 XML 属性
- kubernetes - Is it possible to Reverse-dns query for a POD IP address to get its hostname for a Kubernetes Deployment?
- postman - 如何在 Postman 中添加集合变量?
- mql - 是否有任何 Mql 命令来打印两个管理对象之间的连接?
- components - 虚幻引擎重新实例化非演员处理确保
- java - Global Keylogger in Java Swing