python List交集 並集 差集

2022-07-17 23:54:18 字數 1256 閱讀 6638

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

b_list = [, ]

ret_list =

for item in

a_list:

if item not

inb_list:

for item in

b_list:

if item not

ina_list:

print(ret_list)

(2)

if

__name__ == '

__main__':

a_list = [, , , , ]

b_list = [, ]

ret_list = [item for item in a_list if item not

in b_list] + [item for item in b_list if item not

ina_list]

print(ret_list)

參考link:

交集並集差集

1 內連線 select from student a inner join sc b on a.sno b.sno 左連線 select from student a left join sc b on a.sno b.sno 差集 select sno from student except s...

shell bash 交集 並集 差集

方法一 直接用檔名 取兩個文字檔案的並集 交集 差集 並 sort m sort file1 uniq sort file2 uniq uniq 交 sort m sort file1 uniq sort file2 uniq uniq d 差 file1 file2 sort m sort fil...

PHP 交集 並集 差集

array flip array splice 並集 array merge 過濾 array filter 去重 array unique 差集 array diff array diff 函式返回兩個陣列的差集陣列。該陣列包括了所有在被比較的陣列中,但是不在任何其他引數陣列中的鍵值。a1 arr...