A set is composed of a set of unordered and non-repeating elements. The specific example is as follows: a
set is represented by braces. The element type can be a number type, a string, or a tuple, but it cannot be a list or a dictionary. The specific examples are as follows:
The collection created with braces is a mutable collection, that is, elements can be added or deleted. In addition, there is also an immutable collection, which does not allow adding or deleting elements.
Next, demonstrate the method of creating these two collections, as shown in the example.
An important use of collections is to remove duplicate elements in some data structures, as shown in the example.
The result of the operation is shown in the figure.
6.5 Common operations of collections
Similar to other data types, collections also have a series of commonly used operations, such as adding elements, deleting elements, and so on. Through these operations, the collection can be easily processed.
6.5.1 Adding elements To add elements to the
collection, you can use the add() and update() functions, as shown in the example.
The result of the operation is shown in the figure.
6.5.2 Delete elements To delete elements in the
collection, you can use the remove() and discard() functions, as shown in the example.
The result of the operation is shown in the figure.
6.5.3 Set operations
Sets can participate in a variety of operations, as shown in the table.
Next, demonstrate the usage of these operations, as shown in the example.
In addition to the above operators, the union(), intersection(), and difference() functions can also be used to realize the union, intersection, and difference of sets, as shown in the example.
The result of the operation is shown in the figure.
6.5.4 Set Traversal
The collection can be traversed through the elements of the for loop, as shown in the example.
The result of the operation is shown in the figure.
Dictionary derivation is similar to list derivation. It derives a dictionary. The specific example is as follows:
dictionary derivation is surrounded by braces and requires two expressions, one to generate key and one to generate value. The two expressions are separated by a colon. The result is returned to the dictionary. If you print dict1 through print(), the output will be: The
above is a simple dictionary derivation, and then a slightly more complicated dictionary derivation will be demonstrated, as shown in the example.
The result of the operation is shown in the figure.
Set comprehension is also similar to list comprehension, just change the square brackets to curly braces. The specific example is as follows:
Set comprehension will return a set. If set1 is printed by print(), the output result is:
Next, demonstrate the usage of set derivation, as shown in the example.
The result of the operation is shown in the figure.