Operation of Python collection

Atwo 2020-11-17 12:54:54
operation python collection

list_1 = [1, 4, 5, 7, 3, 6, 7, 9]
print(list_1, type(list_1))
list_1 = set(list_1) # Convert list to set

Assembly is born to remove heavy
print(list_1)
list_2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
list_3 = set([2, 0, 66, 22, 8])

intersection
print(list_1.intersection(list_2))
print(list_1 & list_2)

Combine
print(list_1.union(list_2))
print(list_1 | list_2)

Difference set ( Pay attention to the logical order )
print(list_1.difference(list_2))
print(list_2.difference(list_1))
print(list_1 - list_2)
print(list_2 - list_1)

A subset of
print(list_1.issubset(list_2))
print(list_1 <= list_2)
print(list_1.issuperset(list_2))

Symmetric difference set Get rid of all the repetition Not a single copy
print(list_1.symmetric_difference(list_2))
print(list_1 ^ list_2)

Judge whether there is intersection
print(list_3.isdisjoint(list_1))

Add, delete, modify and query the set
list_1.update([11, 12, 13])
list_1.remove(7)
list_1.pop() # Random delete
list_1.discard(8) # Delete if there is If not , Don't complain

Judge if it's in the set
print(6 in list_1)
print(8 in list_1)
print(8 not in list_1)
print(list_1)
print(len(list_1))