Python Advanced tutorial Set data structure

Source: Internet
Author: User


Set (set) is a very useful data structure. It behaves like a list, except that a set cannot contain duplicate values.
This is useful in many cases. For example, you might want to check if the list contains duplicate elements, you have two choices, and the first one needs to use a For loop, like this:

#use a For loop to check for duplicate elementsSome_list = ['a','b','C','b','D','m','N','N','b']dup= [] forValueinchsome_list:ifSome_list.count (value) >2:        ifValue not inchdup:dup.append (value)PrintDup

Output Result:

C:\Python27\python.exe e:/python/testspider/fibon.py['b']

But there is a simpler and more elegant solution, which is to use the collection (sets), which you do directly:

#finding repeating elements using the Set functionSome_list = ['a','b','C','b','D','m','N','N','b']dup= Set ([x forXinchSome_listifSome_list.count (x) >2])Print(DUP)

Output:

C:\Python27\python.exe e:/python/testspider/fibon.pyset (['b'])

The Set function can also find the intersection in an element

#Set Lookup intersectionvalid = Set (['Yellow','Red','Blue','Green','Black']) Input_set= Set (['Red','Brown'])Print(input_set.intersection (valid))

Output

C:\Python27\python.exe e:/python/testspider/fibon.pyset (['red'])

Set function find two element difference set

#Set Lookup difference setvalid = Set (['Yellow','Red','Blue','Green','Black']) Input_set= Set (['Red','Brown'])Print(input_set.difference (valid))

Output:

C:\Python27\python.exe e:/python/testspider/fibon.pyset (['Brown'])

Python Advanced tutorial Set data structure

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.