Python integration type (set) Learning summary, pythonset
Set is an unordered element set that supports parallel, intersection, difference, and symmetry difference mathematical operations. However, because set does not record the element location, it does not support operations such as index and sharding.
Initialization
Copy codeThe Code is as follows:
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 ))
Running result:
Copy codeThe Code is as follows:
Set () {0} {0, 1} {'I', 'H'} {'E', 'O', 'l ', 'H'} <class 'dict '>
Prompt
1. s0, d0: Use {} to create only empty dictionaries. You must use set () to create empty sets ();
2. ss and sl: Elements in the set are unordered and repeat-free. You can use this feature to remove repeated elements in the list.
Operation
Copy codeThe Code is as follows:
Print (s. intersection (t), s & t) # intersection
Print (s. union (t), s | t) # union
Print (s. difference (t), s-t) # difference set
Print (s. symmetric_difference (t), s ^ t) # symmetric difference set
Print (s1.issubset (s2), s1 <= s2) # subset
Print (s1.issuperset (s2), s1> = s2) # contains
Running result:
Copy codeThe Code is as follows:
{'H '}
{'L', 'h', 'I', 'O', 'E'} {'l', 'h', 'I', 'O', 'O ', 'E '}
{'I '}
{'I', 'l', 'O', 'E'} {'I', 'l', 'O', 'E '}
True
False
Prompt
1. Non-Operator Methods accept any iteratable objects as parameters, such as s. update ([0, 1]);
2. other equivalent operations: s. update (t) and s | = t, s. intersection_update (t) and s & = t, s. difference_update (t) and s-= t, s. symmetric_difference_update (t) and s ^ = t.
Basic Method
Copy codeThe Code is as follows:
S = {0}
Print (s, len (s) # obtain the total number of elements in the Set
S. add ("x") # add an element
Print (s)
S. update ([1, 2, 3]) # add multiple elements
Print (s, "x" in s) # member Qualification Test
S. remove ("x") # remove an element
Print (s, "x" not in s)
S. discard ("x") # If a specified element exists in the Set, delete the element.
C = s. copy () # copy a set
Print (s, s. pop () # An uncertain element in the set is displayed. If the original set is empty, KeyError is thrown.
S. clear () # Delete elements in the Set
Print (s, c)
Running result:
Copy codeThe Code is as follows:
{0} 1
{0, 'x '}
{0, 'x', 1, 2, 3} True
{0, 1, 2, 3} True
{1, 2, 3} 0
Set () {0, 1, 2, 3}