Python Data Type-collection (set)

Source: Internet
Author: User
Tags iterable

1. Create a Collection

Collections are created differently than the first two data structures.

The collection is created by the set (Iterable) method, and the parameter iterable is an iterative object.

Example code:

S1 = set (' Learn every day ')  # Break a string into a single character, create a collection as an element of a collection S2 = set ((' Good ', ' learn ', ' everyday ', ' think on ')  #) # breaks a tuple into a single element, creates a collection as a collection element s3 = Set ( [' Good ', ' learn ', ' everyday ', ' want on ']  # Break the list into a single element, create a collection as a collection element print (S1)  # Displays the output as: {' good ', ' XI ', ' on ', ' Day ', ' think ', ' learn '}print (S2)  # Show output as: {' good ', ' want on ', ' learn ', ' Every day '}print (S3)  # shows the output as: {' good ', ' want to ', ' learn ', ' every day '}

Through the above example, you can see:

    • Collections can be created by iterating over objects (strings, tuples, lists, and so on);
    • The elements in the collection are not repeatable;
    • Unordered array of elements in the collection.

2. Adding elements

There are two ways to add elements to a collection.

Add a single element: using the Add (element) function, the parameter element is the element that the collection allows to add (for example, numbers, strings, tuples, and so on).

Add multiple elements: Using the update (iterable) function, the parameter is iterable as an iterative object.

Example code:

# Create Collection S1 = Set (' 123 ') s2 = set (' 123 ') s3 = set (' abc ') # Add a single element S1.add (' 4 ') # Add multiple elements s2.update ([' 4 ', ' 5 ', ' 6 '])  # Add list to collection, The list element is decomposed into a single element after it is added to the collection s3.update (' de ')  # Add string to the collection, the string is decomposed into a single element after it is added to the collection # Display output print (S1)  # Display output is: {' 4 ', ' 3 ', ' 1 ', ' 2 '}print (S2)  # shows the output as: {' 4 ', ' 2 ', ' 6 ', ' 5 ', ' 3 ', ' 1 '}print (S3)  # show the output as: {' C ', ' B ', ' d ', ' e ', ' A '} #注意: Because the set element is unordered, When you test the above code, the results of the display output and the results above may be inconsistent in order.

3. Deleting elements

There are two ways to delete an element in a collection.

The first: Remove the specified element using the Remove (element) method, which is the element that needs to be deleted.

Second: Use the Discard (element) method to delete the specified element, which is the element that needs to be deleted.

Example code:

# Create Collection S1 = set ([' Python ', ' Java ', ' C ', ' C + + ', ' C # ')) s2 = set ([' Python ', ' Java ', ' C ', ' C + + ', ' C ']) # Delete element S1.remove (' C + + ') S2.discard (' C + + ') # Display output print (S1)  # shows output as: {' C ', ' Python ', ' Java ', ' C # '}print (S2)  # Display output as: {' C ', ' Python ', ' Java ', ' C # '}

From the example above, you can see that the action of remove () and discard () is the same.

However, there is a difference between the two methods.

The Remove () method throws an exception when the elements that are filled in the two method arguments do not exist in the collection, and the Discard () method has no effect.

4. Remove the Element

The collection supports the Pop () method to take out elements.

Example code:

# Create Collection S = Set ([' Python ', ' Java ', ' C ', ' C + + ', ' C # ') # Display output print (s)  # Display output as: {' Python ', ' C # ', ' C + + ', ' Java ', ' C '}print (s . Pop ()) # takes out the collection element and displays the output as: Pythonprint (s)  # Displays the output as: {' C # ', ' C + + ', ' Java ', ' C '}

5. Clear the collection

The collection supports the clear () method for emptying.

Example code:

# Create Collection S = Set ([' Python ', ' Java ', ' C ', ' C + + ', ' C # ') # Empty Collection s.clear () # Display output print (s)  # Display output: Set ()

6. Intersection/set/complement/difference set

First, we take a look at a graph to understand the concepts of intersection, set, complement, and difference sets.

Suppose there are collections a{1,2,3} and b{3,4,5}.

Intersection: Contents of the same part in A and B, {3}.

The same set: A and B all contents after the re-weight, {1,2,3,4,5}.

Complement: A removes the content after the intersection with B, {.

Difference set: The entire contents of a and B disjoint portions, {1,2,4,5}.

Example code:

# Create Collection S1 = Set (' Python ') s2 = set (' Pycharm ') # intersection operation: Gets two sets of elements. Print (S1 & S2)  # shows the output as: {' Y ', ' P ', ' H '}print (s1.intersection (S2))  # Show output as: {' Y ', ' P ', ' h '}# set operation: Get two sets removed All elements after repeating the element. Print (S1 | s2)  # shows the output as: {' Y ', ' a ', ' C ', ' o ', ' P ', ' n ', ' t ', ' m ', ' R ', ' H '}print (s1.union (S2))  # Show output as: {' Y ', ' A ', ' C ', ' o ', ' P ', ' n ', ' t ', ' m ', ' R ', ' H '}#: Gets the current set of all elements after removing the intersection element with another set. Print (S1-S2)  # shows the output as: {' o ', ' t ', ' n '}print (s1.difference (S2))  # Display output: {' o ', ' t ', ' n '}print (S2-S1)  # The result of the display output is: {' m ', ' a ', ' R ', ' C '}print (S2.difference (S1))  # Display output: {' m ', ' a ', ' R ', ' C '}# difference set operation: Gets two sets all elements after the intersection element is removed.  Print (s1 ^ s2) # shows the output as: {' o ', ' t ', ' m ', ' a ', ' R ', ' N ', ' C '}print (s1.symmetric_difference (S2))  # Show output as: {' o ', ' t ', ' m ', ' a ', ' R ', ' N ', ' C '}

In the above operation, the contents of the collection itself is not affected, you can execute the above code, continue to display the output S1 and S2 content, can see no changes.

Next, let's look at a few more methods that will change the contents of the collection.

The first: the Difference_update (set) function, which is able to perform a complement operation on the current collection and the specified collection, and updates the current collection contents to the result of the operation.

Example code:

S1=set (' 1234 ') s2=set (' 456 ') s1.difference (S2) # This operation has no effect on S1 content print (S1) # S1 No change, display output is: {' 3 ', ' 4 ', ' 2 ', ' 1 '}s1.difference _update (S2) # Updates the contents of the collection S1 after the S1-S2 result print (S1) # S1 content is updated, showing output as: {' 3 ', ' 2 ', ' 1 '}

The second type is the intersection_update (set) function, which enables the intersection of the current collection and the specified collection and updates the contents of the current collection to the result of the operation.

Example code:

S1=set (' 1234 ') s2=set (' 456 ') s1.intersection_update (S2) # Update the contents of the collection S1 after S1 & S2 The result of print (S1) # S1 The content is updated to show the output as: {' 4 '}

The third type: the Symmetric_difference_update (set) function, which enables the difference between the current collection and the specified set, and updates the current collection contents to the result of the operation.

Example code:

S1 = set (' 1234 ') s2 = set (' 456 ') s1.symmetric_difference_update (S2)  # Update the contents of the collection S1 S1 ^ s2 After the result of print (S1)  # S1 content is updated, The display output is: {' 6 ', ' 3 ', ' 2 ', ' 5 ', ' 1 '}

7. Member relations

Python provides methods that allow us to determine whether a collection contains an element;

You can also determine whether a collection is a subset or a superset of another collection.

You can also tell if a collection has no intersection with another collection.

Before we approached the "in" operator, it was possible to determine whether the value in front of the operator was included in the sequence behind it (the membership).

In addition, we can also use "not in" to determine whether the value in front of the operator is not contained in the rear sequence (non-member relationship).

In the collection, we can also use these two operators.

In addition, we can determine whether a collection is a subset or a superset of another set, and there is no intersection with the following methods.

Isdisjoint (SET): can determine whether the collection does not have an intersection with the specified set, the parameter set is a set, or false if the result of the set returns True.

Issubset (SET): You can determine whether the collection specifies a subset of the set, the parameter set is a set, or false if the result of the set returns True.

Issuperset (SET): You can determine whether the collection specifies a superset of the set, the parameter set is a set, or false if the result of the set returns True.

Example code:

S1 = set (' Good learning ') s2 = set (' Think on it every day ') s3 = Set (' Learn every day ') print (' OK ' in S1) # Displays the output as: Trueprint (' good ' not in S2) # shows the output as: Truepr Int (s1.isdisjoint (s2))  # shows output as: Trueprint (S1.issubset (S3))  # Show Output as: Trueprint (S3.issuperset (S1))  # Display output is: True

8. Copy the collection

Use the copy () method to copy a collection.

You can understand the purpose of replication using the code below.

Example code:

A = set (' Small building one night listening to Spring language ')  # Create a collection save variable ab = a  # Create variable b reference variable a set c = A.copy (  ) # Create variable c copy variable a value print (a)  # show output as: {' Spring ', ' Night ' ', ' Lou ', ' Listen ', ' language ', ' small ', ' one '}print (b)  # Show output as: {' Spring ', ' Night ', ' floor ', ' listen ', ' language ', ' small ', ' one '}print (c)  # Show output as: {' Spring ', ' Night ', ' Building ', ' listen ', ' language ', ' small ', ' One '}a.remove (' one ')  # Delete an element of the collection in variable a print (a)  # variable A changes, showing the output as: {' Spring ', ' Night ', ' Lou ', ' Listen ', ' language ', ' small '}prin T (b)  # variable B because the reference variable a, the same changes, the display output is: {' Spring ', ' Night ', ' Lou ', ' Listen ', ' language ', ' small '}print (c)  # variable C does not change, display output as: {' Spring ', ' Night ', ' Lou ', ' Listen ', ' Language ', ' small ', ' one '}

If it is not understood, we can look at the picture below.

In the code, B = A actually points B to the content of a, so when the content of a changes, b synchronization changes.

c = A.copy () is a real copy of the content of a, no longer affected by the change of a.

9. Other

The collection also supports the Len () method to get the number of elements, and the Max () method and the Min method to get the largest and smallest elements in the collection, not to repeat

Python Data Type-collection (set)

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.