工作中遇到了求兩個集合的差集,但是集合集合中包含字典,所以使用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)
