1. Get the intersection of two lists
print list(set(a).intersection(set(b)))
2. Get the union of two lists
print list(set(a).union(set(b)))
3. Get the difference of two lists
print list(set(b).difference(set(a))) # There is in b but not in a
2.python Set intersection, union, difference
s = set([3,5,9,10,20,40]) #Create a numeric set
t = set([3,5,9,1,7,29,81]) #Create a set of values
a = t | s # The union of t and s, equivalent to t.union(s)
b = t & s # The intersection of t and s, equivalent to t.intersection(s)
c = t-s # Difference set (item is in t, but not in s), equivalent to t.difference(s)
d = t ^ s # Symmetric difference set (items are in t or s, but will not appear in both), equivalent to t.symmetric_difference(s)
@差集(Dictionary)
(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)