Python learning notes-Set

Source: Internet
Author: User
ArticleDirectory
    • Create a set
    • Update set
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] 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.