python List交集、并集、差集
工作中遇到了求兩個集合的差集,但是集合集合中包含字典,所以使用difference方法會報錯,看了一些別人的博客,整理了一下。
?
1. 獲取兩個list 的交集
print list(set(a).intersection(set(b)))
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
轉載于:https://www.cnblogs.com/jingtyu/p/7238743.html
總結
以上是生活随笔為你收集整理的python List交集、并集、差集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unity shader学习之屏幕后期处
- 下一篇: websocket python爬虫_p