Python basics 7 -- set, python7 -- Set

Source: Internet
Author: User

Python basics 7 -- set, python7 -- Set

Set

The set in Python is an unordered, non-repeating element set. Basic functions include link testing and deduplication. The Set object also supports mathematical operations such as union, intersection, difference, and sysmmetric differencr.

Set supports x in set, len (set), and for x in set. As an unordered set, set does not record the subscript of the element.

Example:

1. Set Operations

1. Create a set

1 list1 = set('bigberg')2 list2 = set('smallberg')3 print(list1,type(list1))4 print(list2,type(list2))

 

2. add the element to be passed in to the set as a whole.

1 a = set('lion')2 a.add('rabbit')3 print(a)

 

3. Add update to the set to split the elements to be passed in and insert them into the set as an individual.

1 b = set('lion')2 b.update('rabbit')3 print(b)

 

4. remove a collection

1 a = set('lion')2 a.add('rabbit')3 print(a)4 5 a.remove('rabbit')6 print(a)

 

Ii. Set relationships

1. Union (deduplication)

1 a = {1, 2, 3, 3, 66} 2 B = {3, 4, 5, 6, 33} 3 4 print (a. union (B) # print (a | B)

{33, 2, 66, 3, 4, 1, 5, 6} # only one copy of the same part is retained.

 

2. Intersection

1 a = {1,2,3,4,33,66}2 b = {3,4,5,6,33}3 4 print(a.intersection(b))5 print(a & b)

{33, 3, 4}
{33, 3, 4}

 

3. difference set

1 a = {1,2,3,4,33,66}2 b = {3,4,5,6,33}3 4 print(a.difference(b))5 print(b.difference(a))   # print(b - a)

{1, 2, 66}
{5, 6}

 

4. Relative population

1 a = {1, 2, 3, 3, 66} 2 B = {3, 4, 5, 6, 33} 3 4 print (. effecric_difference (B) # Remove the same element 5 print (B. symmetric_difference ())

{1, 2, 5, 6, 66}
{2, 66, 5, 1, 6}

 

5. subset and parent set

1 a = {1, 2, 3, 3, 66} 2 B = {3, 4, 5, 6, 33} 3 4 print (. issubset (B) # subset 5 print (B. issuperset (a) # parent set

False
False

 

Related Article

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.