• python 关于两个list的交、差、补集 运算


    本文主要介绍在Python下求两个list的交集、并集、差(补)集、对称差集的方法。首先,总结了实现上述功能主要的两种方法:1.使用set集合运算符,2.使用set集合的方法(推荐第2种方法)

    1. 总结
    1.1 求两个list的交、并、差(补)、对称差集 - 使用set集合运算符
    输入:

    a = [0,1,2,3,4]
    b = [0,2,6]
    list(set(a) & set(b)) # 使用 "&" 运算求a与b的交集,输出:[0, 2]
    list(set(a) | set(b)) # 使用 "|" 运算求a与b的并集,输出:[0, 1, 2, 3, 4, 6]
    list(set(b) - set(a)) # 使用 "-" 运算求a与b的差(补)集: 求b中有而a中没有的元素,输出:[6]
    list(set(a) - set(b)) # 使用 "-" 运算求a与b的差(补)集: 求a中有而b中没有的元素,输出:[1, 3, 4]
    list(set(a) ^ set(b)) # 使用 "^" 运算求a与b的对称差集,输出:[1, 3, 4, 6]

    输出:

    求交集: list(set(a) & set(b)) 输出 -> [0, 2]
    求并集: list(set(a) | set(b)) 输出 -> [0, 1, 2, 3, 4, 6]
    求差(补)集: list(set(b) - set(a)) 输出 -> [6]
    求差(补)集: list(set(a) - set(b)) 输出 -> [1, 3, 4]
    求对称差集: list(set(a) ^ set(b)) 输出 -> [1, 3, 4, 6]

    1.2 求两个list的交、并、差(补)、对称差集 - 使用set集合的方法 - 高效率
    输入:

    a = [0,1,2,3,4]
    b = [0,2,6]
    list(set(a).intersection(set(b))) # 使用 intersection 求a与b的交集,输出:[0, 2]
    list(set(a).union(b)) # 使用 union 求a与b的并集,输出:[0, 1, 2, 3, 4, 6]
    list(set(b).difference(set(a))) # 使用 difference 求a与b的差(补)集:求b中有而a中没有的元素,输出: [6]
    list(set(a).difference(set(b))) # 使用 difference 求a与b的差(补)集:求a中有而b中没有的元素,输出:[1, 3, 4]
    list(set(a).symmetric_difference(b)) # 使用 symmetric_difference 求a与b的对称差集,输出:[1, 3, 4, 6]

    输出:

    求交集:list(set(a).intersection(set(b)) 输出 --> [0, 2]
    求并集:list(set(a).union(b)) 输出 --> [0, 1, 2, 3, 4, 6]
    求差(补)集: list(set(b).difference(set(a)) 输出 --> [6]
    求差(补)集: list(set(a).difference(set(b))) 输出 --> [1, 3, 4]
    求对称差集: list(set(a).symmetric_difference(b)) 输出 --> [1, 3, 4, 6]


  • 相关阅读:
    C#通过文件头判断图像格式(摘录)
    devenv.exe 应用程序错误
    LINQ TO SQL中的selectMany(转)
    DragDrop registration did not succeed. (摘录)
    API各函数作用简介(转)
    Linq递归用法(摘录)
    (转)逐步为对象集合构建一个通用的按指定属性排序的方法
    何止 Linq 的 Distinct 不给力(转)
    关于sql日志文件
    DES算法的C#实现
  • 原文地址:https://www.cnblogs.com/DJRemix/p/12691044.html
Copyright © 2020-2023  润新知