zoukankan      html  css  js  c++  java
  • 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]


  • 相关阅读:
    Microsoft Security Essentials
    android studio 引用远程仓库下载慢(JCenter下载慢)的办法
    Android studio Unable to start the daemon process
    Android studio 怎么使用已经下载好的Android SDK ?
    解决Unknown error: Unable to build: the file dx.jar was not loaded from the SDK folder!
    U3d中实现A*寻路,附源文件
    [运维-服务器 – 1A] – nginx.conf(转)
    unity客户端与c++服务器之间的简单通讯_1
    [Java Web – Maven – 1A]maven 3.3.3 for windows 配置(转)
    [Android-2A] -仿IOS微信滑动删除_SwipeListview左滑删除例子
  • 原文地址:https://www.cnblogs.com/DJRemix/p/12691044.html
Copyright © 2011-2022 走看看