Collection type (set) learning summary in Python

  • 2020-04-02 14:31:19
  • OfStack

Set is an unordered set of elements, which supports mathematical operations such as union, intersection, difference and symmetry difference. However, since set does not record the position of elements, it does not support the operations of index, shard and other sequences.

Initialize the


s0 = set()
d0 = {}
s1 = {0}
s2 = {i % 2 for i in range(10)}
s = set('hi')
t = set(['h', 'e', 'l', 'l', 'o'])
print(s0, s1, s2, s, t, type(d0))

Operation results:

set() {0} {0, 1} {'i', 'h'} {'e', 'o', 'l', 'h'} <class 'dict'>

prompt
1. S0, d0: the use of {} can only create an empty dictionary, the creation of an empty set must use set();
2. The elements in ss, sl: set are unordered and unrepeated, which can be used to remove the repeated elements in the list.

Arithmetic operations


print(s.intersection(t), s & t)  # intersection
print(s.union(t), s | t)   # And set
print(s.difference(t), s - t)  # Difference set
print(s.symmetric_difference(t), s ^ t) # Symmetric difference set
print(s1.issubset(s2), s1 <= s2) # A subset of
print(s1.issuperset(s2), s1 >= s2)      # contains

Operation results:


{'h'} {'h'}
{'l', 'h', 'i', 'o', 'e'} {'l', 'h', 'i', 'o', 'e'}
{'i'} {'i'}
{'i', 'l', 'o', 'e'} {'i', 'l', 'o', 'e'}
True True
False False

prompt
1. Non-operator methods accept any iterable object as a parameter, such as s.date ([0, 1]);
2. Other equivalent operations: s.date (t) and s |= t, s & s tersection_update(t) and s &= t, s.fference_update (t) and s -= t, s.s.mmetric_difference_update (t) and s ^= t, etc.

Basic method


s = {0}
print(s, len(s))   # Gets the total number of elements in the collection
s.add("x")         # Add an element
print(s)
s.update([1,2,3])  # Add multiple elements
print(s, "x" in s) # Membership test
s.remove("x")      # Get rid of an element
print(s, "x" not in s) 
s.discard("x")     # Deletes the specified element if it exists in the collection
c = s.copy()       # Copying collection     
print(s, s.pop())  # An uncertain element in the pop-up collection, thrown if the original set is empty KeyError
s.clear()          # Delete the elements in the collection
print(s, c)

Operation results:

{0} 1
{0, 'x'}
{0, 'x', 1, 2, 3} True
{0, 1, 2, 3} True
{1, 2, 3} 0
set() {0, 1, 2, 3}


Related articles: