Python set

1.Method for creating a set

 1)s={1,"python"}
 2)s=set("python") or s=set([1,"python"])
   ps. set to list: 
                   lst=list(s)
       list to set(can remove duplicate elements from the set):
                   s=set([1,"python"])  
       Create an immutable set in "frozenset"

2.Common method of set

 1)add 
    eg.
    b=set()
    b.add("python")
 2)update
    eg.
    >>>seta={"wiki","twitter","google","facebook"}
    >>>setb={"python",(1,2,3)}
    >>>seta.update(b)
    >>>seta
    >>>set(["wiki","twitter","google","python","facebook",(1,2,3)])
 3)pop
    eg. 
    >>>seta={"wiki","twitter","google","facebook"}
    >>>seta.pop()#Random deletion of an element
 4)remove
    eg.
    >>>seta={"wiki","twitter","google","facebook"}
    >>>seta.remove("wiki")#delete the element´╝îIf it does not exist, it will be reported to the wrong
 5)discard
    eg.
    >>>seta={"wiki","twitter","google","facebook"}
    >>>seta.discard("wiki")
    >>>seta.discard("wiki")#If it does not exist, it will not be reported to the wrong
 6)clear
    eg.
    >>>seta={"wiki","twitter","google","facebook"}
    >>>seta.clear()
    >>>seta
    set([])

3.Operations With Set

 1)To determine whether an element is in the set.
     eg.
     >>> s = set([1,2,3,4])
     >>> 1 in s
     True
     >>> 5 in s
     False
 2)Judge whether the two sets are equal.
     eg.
     >>> a = set([1,2,3,4,5])
     >>> b = set([1,2,3,4,5])
     >>> a ==b
     True
     >>>b.pop()
     1
     >>>b
     set([2,3,4,5])
     >>>a==b
     False  
 3)To determine whether a subset
     eg.
     >>> a = set([1,2,3,4])
     >>> b = set([1,2,3,4,5])    
     >>>a < b
     True
     >>>a.issubset(b)
     True
 4)To determine whether a superset
     eg.
     >>> a = set([1,2,3,4])
     >>> b = set([1,2,3,4,5])    
     >>>b > a
     True
     >>>b.issuperset(a)
     True 
 5)To get the union set
     eg.
     >>> a = set([0,1,3,4,6])
     >>> b = set([1,2,3,4,5])
     >>> a | b
     set([0,1,2,3,4,5,6])
     >>> a.union(b)
     set([0,1,2,3,4,5,6])
 6)To get the intersection
     eg.
     >>> a = set([0,1,3,4,6])
     >>> b = set([1,2,3,4,5])
     >>> a & b
     set([1,3,4])
     >>> a.intersection(b)
     set([1,3,4])
 7)To get the difference for the other set 
     eg.
     >>> a = set([0,1,3,4,6])
     >>> b = set([1,2,3,4,5])
     >>> a - b
     set([0,6])
     >>> a.difference(b)
     set([0,6])
 8)To get the union of difference sets
     eg.
     >>> a = set([0,1,3,4,6])
     >>> b = set([1,2,3,4,5])
     >>> a.symmetric_difference(b)
     set([0,6,2,5])

Pingbacks are closed.

Comments are closed.