python中列表元素求交集和并集

 

>>> test1 = ["aaa","bbb","ccc","ddd","eee","fff"]
>>> test2 = ["ddd","eee","fff","ggg","hhh","iii"]
>>> test3 = test1 + test2
>>> test3
['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii']
>>> test4 = []
>>> for i in test3:    ## 求交集
    if i not in test4:
        test4.append(i)

        
>>> test4
['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii']
>>> test5 = []
>>> for i in test1:    ## 求并集
    if i in test2:
        test5.append(i)

        
>>> test5
['ddd', 'eee', 'fff']
>>> test6 = []
>>> for i in test1:   ## 求单侧并集
    if i not in test2:
        test6.append(i)

        
>>> test6
['aaa', 'bbb', 'ccc']

 

posted @ 2020-12-18 22:20  小鲨鱼2018  阅读(934)  评论(0编辑  收藏  举报