Interpretation of basic Python set applications

Source: Internet
Author: User

The role of the Python programming language is very obvious in practical applications, and its easy-to-use features are also very convenient for programmers. Today, we can take a look at the application characteristics of this language from the Python set type. The Python set type is an important application type, and sometimes it is quite useful. For detailed documentation and instructions, you can use help (set) to view the instructions and methods.

The following is a simple example.

 
 
  1. >>> x = set('spam')  
  2. >>> y = set(['h','a','m'])  
  3. >>> x, y  
  4. (set(['a', 'p', 's', 'm']), set(['a', 'h', 'm'])) 

Let's look at some small Python set applications.

 
 
  1. >>> X & y # intersection
  2. Set (['A', 'M'])
  3. >>> X | y # Union
  4. Set (['A', 'P', 's', 'h', 'M'])
  5. >>> X-y # difference set
  6. Set (['P', 's'])

I remember a previous netizen asking how to remove repeated elements from the massive list and use hash to solve the problem. However, I felt that the performance was not very high and it was good to use set. The example is as follows:

 
 
  1. >>> a = [11,22,33,44,11,22]  
  2. >>> b = set(a)  
  3. >>> b  
  4. set([33, 11, 44, 22])  
  5. >>> c = [i for i in b]  
  6. >>> c  
  7. [33, 11, 44, 22] 

It's cool, just a few lines. The above is the Python set type method we will introduce to you.

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.