zoukankan      html  css  js  c++  java
  • python List交集、并集、差集

    工作中遇到了求两个集合的差集,但是集合集合中包含字典,所以使用difference方法会报错,看了一些别人的博客,整理了一下。

    1. 获取两个list 的交集
    print list(set(a).intersection(set(b)))

    2. 获取两个list 的并集
    print list(set(a).union(set(b)))
    3. 获取两个 list 的差集

    print list(set(b).difference(set(a))) # b中有而a中没有的

    2.python Set交集、并集、差集

    s = set([3,5,9,10,20,40])      #创建一个数值集合 

    t = set([3,5,9,1,7,29,81])      #创建一个数值集合 

    a = t | s          # t 和 s的并集 ,等价于t.union(s)

    b = t & s          # t 和 s的交集 ,等价于t.intersection(s) 

    c = t - s          # 求差集(项在t中,但不在s中)  ,等价于t.difference(s) 

    d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中),等价于t.symmetric_difference(s)

    @差集(字典)

    (1)

    if __name__ == '__main__':
        a_list = [{'a' : 1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}]
        b_list = [{'a' : 1}, {'b' : 2}]
        ret_list = []
        for item in a_list:
            if item not in b_list:
                ret_list.append(item)
        for item in b_list:
            if item not in a_list:
                ret_list.append(item)
        print(ret_list)

    (2)

    if __name__ == '__main__':
        a_list = [{'a' : 1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}]
        b_list = [{'a' : 1}, {'b' : 2}]
        ret_list = [item for item in a_list if item not in b_list] + [item for item in b_list if item not in a_list]
        print(ret_list)

    参考link:http://www.cnblogs.com/DjangoBlog/p/3510385.html

                    http://www.jb51.net/article/93166.htm

  • 相关阅读:
    转:matplotlib画图,plt.xx和ax.xx之间有什么差异
    转:Python __call__()方法,可调用对象
    训练集,验证集,测试集,交叉验证
    Visio画图和导出图的时候,去除多余白色背景
    在线jupyter notebook
    dfs序
    codeforces 877b
    codeforce864d
    codeforce868c
    查看本地git查看git公钥,私钥的方式
  • 原文地址:https://www.cnblogs.com/jingtyu/p/7238743.html
Copyright © 2011-2022 走看看