Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create collections of common data structures in Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to create a collection of common data structures in Python". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to create a collection of common data structures in Python".

When it comes to the word "set", we must be familiar with it, and there is this concept in math textbooks. Usually our definition of a set is to "treat a certain range, certain, distinguishable things as a whole", and each thing in the set is often called the elements of the set. The collection should meet the following characteristics:

Disorder: in a collection, the status of each element is the same, and the elements are disordered.

Heterogeneity: any two elements in a collection are considered to be different, that is, each element can appear only once.

Certainty: given a set, any element that either belongs to or does not belong to the set must be one or the other, and ambiguity is not allowed.

The set in the Python program is exactly the same as the mathematical set, and the disorder and heterogeneity mentioned above need to be emphasized. Disorder means that the elements in the collection are not as close to each other as the elements in the column, and can be accessed randomly by index (random access means that given a valid range, randomly extract a number, and then get the corresponding element through this number), so the set in Python certainly can not support index operation. In addition, the heterogeneity of the set determines that there can be no duplicate elements in the set, which is also the key to distinguish the collection from the list. To put it more bluntly, the collection type in Python has the property of deduplication. Of course, the set in Python must support the operation of in and not in members, so that you can determine whether an element belongs to the set, that is, the set certainty mentioned above. The performance of the set member operation is better than that of the list member operation, which is determined by the underlying storage characteristics of the collection. Let's not discuss it here, just write down this conclusion.

Create a collection

In Python, you can use {} literal syntax to create a collection, and you need at least one element in {}, because {} without elements is not an empty collection but an empty dictionary, which we will introduce in the next lesson. Of course, you can also use the built-in function set to create a collection. To be exact, set is not a function, but a constructor for creating collection objects. We'll talk about this in a minute, but we can skip it now. To create an empty collection, you can use set (); you can also convert other sequences to a collection, for example: set ('hello') will result in a collection of four characters (repeated l will be removed). In addition to these two ways, we can also use generative syntax to create collections, just as we used to create lists. You need to know how many elements there are in the collection, or you can traverse the collection elements using the built-in function len; and the for loop.

# literal syntax for creating a collection (repeating elements do not appear in the collection)

Set1 = {1,2,3,3,2}

Print (set1) # {1,2,3}

Print (len (set1)) # 3

# Constructor syntax for creating a collection (what is a constructor later)

Set2 = set ('hello')

Print (set2) # {'hints,' lags, 'oaks,' e'}

# convert a list to a collection (duplicate elements can be removed from the list)

Set3 = set ([1,2,3,3,2,1])

Print (set3) # {1,2,3}

# generative syntax for creating a collection (replace [] of list generation with {})

Set4 = {num for num in range (1,20) if num% 3 = = 0 or num% 5 = = 0}

Print (set4) # {3, 5, 6, 9, 10, 12, 15, 18}

# Loop traversal of collection elements

For elem in set4:

Print (elem)

You need to be reminded that the elements in the collection must be of type hashable. The so-called hashable type refers to the data type that can calculate the hash code, which you can temporarily understand as the unique ID value corresponding to the variable. Usually immutable types are hashable types, such as integers, floats, strings, tuples, and so on, while mutable types are not hashable types, because mutable types cannot determine a unique ID value, so they cannot be placed in the collection. The collection itself is also a mutable type, so it is important to note that the collection cannot be used as an element in the collection.

Operation of a set

Python provides a wealth of operators for set types, including member operation, intersection operation, union operation, difference operation, comparison operation (equality, subset, superset) and so on.

Member operation

You can check whether the element is in the collection through the member operations in and not in, as shown in the following code.

Set1 = {11,12,13,14,15}

Print (10 in set1) # False

Print (15 in set1) # True

Set2 = {'Python',' Java', 'Go',' Swift'}

Print ('Ruby' in set2) # False

Print ('Java' in set2) # True intersection and Union difference Operation

Sets in Python, like mathematical sets, can perform operations such as intersection, union, difference, and so on, and can be manipulated through both operators and method calls, as shown below.

Set1 = {1,2,3,4,5,6,7}

Set2 = {2,4,6,8,10}

# intersection

# method 1: use the & operator

Print (set1 & set2) # {2,4,6}

# method 2: use the intersection method

Print (set1.intersection (set2)) # {2,4,6}

# Union

# method 1: use the | operator

Print (set1 | set2) # {1,2,3,4,5,6,7,8,10}

# method 2: use the union method

Print (set1.union (set2)) # {1,2,3,4,5,6,7,8,10}

# subtraction

# method 1: use the-operator

Print (set1-set2) # {1,3,5,7}

# method 2: use the difference method

Print (set1.difference (set2)) # {1,3,5,7}

# Symmetry difference

# method 1: use the ^ operator

Print (set1 ^ set2) # {1,3,5,7,8,10}

# method 2: use the symmetric_difference method

Print (set1.symmetric_difference (set2)) # {1,3,5,7,8,10}

# method 3: the symmetric difference is equal to the union of two sets minus the intersection

Print ((set1 | set2)-(set1 & set2)) # {1,3,5,7,8,10}

As you can see from the above code, the & operator and the intersection method do exactly the same for the intersection of two sets, using the operator is more intuitive and the code is shorter. I believe that the concepts of intersection, union, difference and symmetry difference are relatively clear. If you don't have any impression, you can take a look at the following picture.

The intersection, union, and difference operations of sets can also be combined with assignment operations, as shown below.

Set1 = {1,3,5,7}

Set2 = {2,4,6}

# merge set1 and set2 and assign them to set1

# can also be implemented through set1.update (set2)

Set1 | = set2

Print (set1) # {1,2,3,4,5,6,7}

Set3 = {3,6,9}

# intersection of set1 and set3 and then assign to set1

# can also be implemented through set1.intersection_update (set3)

Set1 & = set3

Print (set1) # {3,6} comparison operation

Two sets can be judged to be equal with = = and! =. If the elements in the two sets are exactly the same, then the result of the = = comparison is True, otherwise it is False. If any element of set An is an element of set B, then set An is called a subset of set B, that is, for ∀ a ∈ A, there is a ∈ B, then A ⊆ B. An is a subset of B. in turn, B can also be called a superset of A. If An is a subset of B and An is not equal to B, then An is a true subset of B. Python provides operators for determining subsets and supersets for collection types, which are actually familiar operators, as shown below.

Set1 = {1,3,5}

Set2 = {1,2,3,4,5}

Set3 = set2

#

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report