The use of set in Python

Source: Internet
Author: User

There are a lot of different data structures in Python, such as list,tuple,set,dic, why do I have to speak set alone?

Because set is a relatively easy-to-forget data structure, not only in Python, but also in C + +, I rarely use set anyway. But after using it, I found the set is actually very powerful. Here are some useful examples of set comparison:

Find the same data in two lists

The first reaction is to traverse a list, get all the data, and then judge it in the second column. The code is as follows:

def Main ():    list1=[1,2,3,4,5]    list2=[3,4,5,6,7]    list3=[]       for in list1:       if in list2:           list3.append (each)     Print List3 if __name__ ' __main__ ' :    main ()

If you use set, it is easy to use intersetion (), it can get the intersection of two set

def Main ():    list1=[1,2,3,4,5]    list2=[3,4,5,6,7]    s1,s2=Set (List1), set ( LIST2)    list3=list (s1.intersection (S2))    print  list3if __name__ ' __main__ ' :    main ()

The same approach would be:

S1.union (S2), which is used to get the set of two sets. That is, the collection of all the elements in the two list.

S1.difference (S2), which is used to get the difference set of two set. That is, a collection that exists in S1 but does not exist in the S2.

S1.symmetric_difference (S2), which is equivalent to s1.union (S2)-s1.intersection (S2). That is, the collection of elements that are not duplicated in S1 and S2.

The use of set in Python

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.