ArticleDirectory
Create a set
Use the factory methods set () and frozenset ():
>>> S = set ('cheeseshop ') >>> sset (['C', 'E', 'h', 'O', 'P ', 'S ']) >>> T = frozenset ('bookshop') >>> tfrozenset ([' B ', 'h', 'k', 'O ', 'P', 's']) >>> type (s) <type 'set' >>>> type (t) <type 'frozenset'>
Update set
Add and delete members of a set using built-in methods and operators of various sets:
>>> S. add ('Z') >>> sset (['C', 'E', 'h', 'O', 'P','s ', 'Z'])> S. update ('pypi ') >>> sset (['C', 'E',' I ', 'h', 'O', 'P','s ', 'y', 'z']) >>> S. remove ('Z') >>> sset (['C', 'E', 'I', 'h', 'O', 'P','s ', 'y']) >>>> S-= set ('pypi ') >>> sset (['C', 'E', 'h', 'O ', 'S '])
Delete collection
Del s
Member relationship (in, not in)
>>> S = set ('cheeseshop') >>> T = frozenset ('bookshop') >>> 'K' in sfalse >>> 'K' in ttrue >>> 'C' not in ttrue
Set equivalence/non-equivalence
>>> S == tfalse >>> s! = Ttrue >>> u = frozenset (s) >>>> S = utrue >>> set ('posh') = set ('shop') True
Difference population/relative population (-)
The difference or relative supplement set of two sets (S and T) refers to a set C. The elements in the set belong to only the set S, not the set T. The difference symbol has an equivalent method, difference ().
>>> S-tset (['C', 'E'])
Symmetric Difference (^): symmetric difference is the XOR of a set.
Remove repeated elements from the list using a set
>> xs = [5, 8, 5, 1, 1, 4, 2, 4, 3, 2] >>> set (XS) Set ([1, 2, 3, 4, 5, 8]) >>>> sorted (SET (XS ), key = Xs. index) # keep the original sequence [5, 8, 1, 4, 2, 3]