Introduction to the set () function and instance parsing in python, pythonset

Source: Internet
Author: User

Introduction to the set () function and instance parsing in python, pythonset

The set function is also one of the python built-in functions, which is a relatively basic function. The detailed introduction and usage are described below.

The set () function creates an unordered, non-repeating element set. It can perform relational tests, delete duplicate data, and compute intersection, difference set, and union.

Set, receives a list as the parameter

List1 = [1, 2, 4] s = set (list1) print (s) # traverse for I in s: print (I) output one by one: set ([1, 2, 3, 4]) 1234

Use add (key) to add elements to the set. duplicate elements are automatically filtered.

List1 = [1, 2, 4] s = set (list1) print (s) s. add (4) s. add (5) print (s) Output: set ([1, 2, 3, 4]) set ([1, 2, 3, 4, 5])

You can use the remove (key) method to delete elements:

List1 = ['A', 'B', 'zhang ', 'Kang'] s = set (list1) print (s) s. remove ('zhang ') print (s) Output: set (['A', 'hang',' B ', 'zhang']) set (['A ', 'hang', 'B'])

Set can also calculate the intersection and union as in Mathematics

List1 = ['A', 'B', 'zhang ', 'hangzhou'] list2 = ['A',' B ', 'C ', 'D'] s1 = set (list1) s2 = set (list2) # intersection, use the & operator s3 = s1 & s2 # Union set, use | Operator s4 = s1 | s2print (s3) print (s4) Output: set (['A', 'B']) set (['A', 'C ', 'B', 'D', 'zhang', 'hangzhou'])

Summary

The above is all about the set () function introduction and instance parsing in python. I hope it will be helpful to you. Interested friends can continue to refer to this site:

Introduction to functions in the Re module of Python Programming"

Python Regular Expression re compile function Parsing"

Parsing the enumerate function code in Python"

If you have any shortcomings, please leave a message. Thank you for your support!

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.