码迷,mamicode.com
首页 > 编程语言 > 详细

python中列表之间求差集、交集、并集

时间:2019-05-17 16:43:59      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:python   for   diff   lis   处理   循环   交集   而且   并集   

求两个列表的交集、并集、差集

    def diff(listA, listB):
        # 求交集的两种方式
        retA = [i for i in listA if i in listB]
        retB = list(set(listA).intersection(set(listB)))
        print("retA is :", retA)
        print("retB is :", retB)
        # 求并集
        retC = list(set(listA).union(set(listB)))
        print("retC is:", retC)
        # 求差集,在B中但不在A中
        retD = list(set(listB).difference(set(listA)))
        print("retD is:", retD)
        retE = [i for i in listB if i not in listA]
        print("retE is:", retE)
    def main():
        listA = [1, 2, 3, 4, 5]
        listB = [3, 4, 5, 6, 7]
        diff(listA, listB)
    if __name__ == '_main_':
        main()
    main()
    ###直接上运行结果
    # retA is : [3, 4, 5]
    #retB is : [3, 4, 5]
    #retC is: [1, 2, 3, 4, 5, 6, 7]
    #retD is: [6,7]
    #retE is: [6, 7]

代码思路:使用列表解析式。列表解析式一般来说比循环快,而且更python,将list转成set以后,使用set的各种方法去处理

python中列表之间求差集、交集、并集

标签:python   for   diff   lis   处理   循环   交集   而且   并集   

原文地址:https://www.cnblogs.com/Dr-wei/p/10882018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!