Use of python set Built in Functions
- 2021-07-06 11:22:09
- OfStack
set Set
Unordered mutability Composed of different elements Its elements must be of hashable type (generally immutable type)Two Definitions of Sets
Use {} Eg: {1, 2, 3, 4, 5} Use the set (iterative type) function Eg: set ("hello") * Creating immutable collections using the frozenset () functionBasic function
s = set("hello")
"""
Add 1 Elements into the collection
"""
s.add('b')
"""
Updating collections with iterative objects
"""
s.update([1,2,3,4])
"""
Empty the collection
"""
s.clear()
"""
Copy set (shallow copy) returns a copy of the copy
"""
s.copy()
"""
Random deletion 1 Elements
Returns if the collection is empty KeyError Anomaly
"""
s = set("hello")
s.pop()
"""
Delete the specified element Errors will be reported if there is no such element
"""
s.remove('e')
"""
Delete the specified element There is no error
"""
s.discard('e')
Set intersection, union, difference and cross complement
s1 = {1,2,3,4,5}
s2 = {1,2,3,6,7}
"""
Intersection
>>> s1.intersection(s2)
{1, 2, 3}
>>> s1&s2
{1, 2, 3}
"""
s1.intersection(s2)
s1&s2
"""
Union
>>> s1.union(s2)
{1, 2, 3, 4, 5, 6, 7}
>>> s1|s2
{1, 2, 3, 4, 5, 6, 7}
"""
s1.union(s2)
s1|s2
"""
Difference set
>>> s1.difference(s2)
{4, 5}
>>> s1-s2
{4, 5}
"""
s1.difference(s2)
s1-s2
"""
Cross complement sets (take their different parts)
>>> s1.symmetric_difference(s2)
{4, 5, 6, 7}
"""
s1.symmetric_difference(s2)
"""
Others update Function
"""
s1.difference_update(s2)
s1.intersection_update(s2)
s1.symmetric_difference_update(s2)
is judgment function
s1 = {1,2,3}
s2 = {1,2}
"""
Returns whether two collections have an intersection
"""
s1.isdisjoint(s2)
"""
Return s1 Whether it is s2 Subset
"""
s1.issubset(s2)
"""
Return s1 Whether it is s2 Parent set
"""
s1.issuperset(s2)