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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM