[Python]集合的交集,并集,差集

前提:测试中需要给某些应用设置黑名单,所以从.txt文件中求两者的差集,就可以筛选出需要测试的应用

思路:将.txt文件中的数据读到list列表中,求列表的交集,再输出到指定目录

一. list操作的思路:

a = [1,2,3,4,5,6]

b = [5,6,7]

c = []

①交集

c = [i for i in a if i in b]   

c = [5,6]

'''

for i in a:                      # i 在a中循环

    if i in b:                    # 如果 i 在b中也存在

        c.append(i)         # 元素 i 添加至c中

'''

②差集

同理:

c1 = [i for i in a if i not in b]        #a中有但b中没有

c1 = [1,2,3,4]

c2 = [i for i in b if i not in a]       #b中有但a中没有 

c2 = [7]

c3 = c1+c2

c3 = [1,2,3,4,7]

二. set操作的思路:

集合(set)是一个无序的不重复元素序列

可以使用大括号 { } 或者 set() 函数创建集合

注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典

a = [1,2,3,4,5,6]

b = [5,6,7]

c = []

①交集

c = list(set(a)&set(b))   or   c = list(set(a).intersection(set(b)))   

c = [5,6]     

②差集

c = list(set(a)-set(b))   or   c = list(set(a).difference(set(b)))      # a中有b中没有

c = [1,2,3,4]

c = list(set(b)-set(a))   or   c = list(set(b).difference(set(a)))      # b中有a中没有

c = [7]

③对称差集

c = list(set(a)^set(b))   or  c = list(set(a).symmetric_difference(set(b)))   

c = [1,2,3,4,7]

④并集

c = list(set(a) | set(b))  or  c = list(set(a).union(set(b)))             # 全部元素

c = [1,2,3,4,5,6,7]

 

posted @ 2018-11-27 17:30  joekk01  阅读(1064)  评论(0编辑  收藏  举报