Skip to main content
 首页 » 编程设计

python之如何在 python 中添加多个集合,但前提是项目是唯一的

2025年05月04日24虾米姐

我需要添加不确定数量的列表(集),但我只想添加唯一的成员

(1,2,3) (3,4,5) (4,7,8,9) (5,3,9)

需要给出:(1,2,7,8)

请您参考如下方法:

from collections import Counter 
from itertools import chain 
 
lst = [(1,2,3), (3,4,5), (4,7,8,9), (5,3,9)] 
 
[k for k, v in Counter(chain.from_iterable(lst)).items() if v==1] 
 
# [1, 2, 7, 8] 

以最低成本,您还可以返回计数为 2、3 等的值。