Detailed explanation of python data structure

Python is a high-level programming language with an easy-to-learn syntax and powerful data structures. In Python, a data structure refers to a collection of data and operations associated with it. Python provides many data structures, including lists, tuples, dictionaries, sets, and strings. This article will give an in-depth introduction to the data structures in Python, hoping to help beginners better understand and use them.

1. List
List is one of the most commonly used data structures in Python, which can store elements with different data types. Creating a list is as simple as enclosing the elements in square brackets [] and separating each element with a comma. For example:

fruits = ['apple', 'banana', 'orange', 'grape']

Lists have many useful features, such as the ability to access elements in a list by subscripting. In Python, subscripts start at 0, for example:

print(fruits[0])  # 输出 'apple'

You can also use the slice operation to get a part of a list. The syntax of the slice operation is a[start:end], which will return the elements from subscript start to subscript end-1 in the list a. For example:

print(fruits[1:3])  # 输出 ['banana', 'orange']

In addition, lists also have many other operations, such as adding elements, removing elements, modifying elements, finding elements, and sorting elements.

2. Tuples
Tuples are similar to lists and can also store elements of different data types, but once created, tuples cannot be modified. The syntax of a tuple is similar to that of a list, and the elements are also placed in parentheses (), and each element is separated by a comma.

fruits = ('apple', 'banana', 'orange', 'grape')

Accessing the elements in a tuple is also similar to a list, and you can use subscripting and slicing operations. For example:

print(fruits[0])  # 输出 'apple'
print(fruits[1:3])  # 输出 ('banana', 'orange')

The immutability of tuples makes them useful for some special purposes, such as keys for dictionaries. In addition, tuples can also be used as the return value of a function to package multiple values ​​into a whole and return them. For example:

def square_and_cube(x):
    return x**2, x**3
    
result = square_and_cube(2)
print(result)  # 输出 (4, 8)

3. Dictionary
A dictionary is an unordered data structure that stores data in the form of key-value pairs. The syntax of a dictionary is to separate keys and values ​​with colons: , separate key-value pairs with commas, and enclose the entire dictionary with curly braces {}. For example:

person = {'name': 'Tom', 'age': 18, 'gender': 'male'}

Accessing elements in the dictionary is done using keys, for example, use person['name'] to access the value corresponding to the 'name' key.

Dictionaries also have many useful methods, such as getting all keys, getting all values, getting all key-value pairs, deleting elements, modifying elements, etc.

4. Collection
A collection is an unordered and non-repetitive data structure. The syntax of a collection is enclosed in curly braces {}, and elements are separated by commas. For example:

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

Sets support some common set operations, such as intersection, union, difference, and symmetric difference. In addition, collections support methods such as adding elements, removing elements, and emptying the collection.

5. String
String is an immutable sequence, which consists of a series of characters. Strings in Python must be enclosed in quotes, either single or double quotes. For example:

s1 = 'hello'
s2 = "world"

Strings support many operations, such as slicing, concatenation, search, and replacement. For example, the slice operation can obtain the substring in the string by subscripting, for example:

s = 'abcdefg'
print(s[1:4])  # 输出 'bcd'

In addition, there are many other methods for strings, such as getting the length of a string, converting between upper and lower case, checking whether a string contains a specified substring, etc. For example:

s = 'hello world'
print(len(s))  # 输出 11
print(s.upper())  # 输出 'HELLO WORLD'
print('world' in s)  # 输出 True

6. Stack
A stack is a data structure with Last In First Out (Last In First Out, LIFO) characteristics. Common stack operations include pushing elements (push), popping elements (pop) and getting the top element of the stack (top). Lists can be used to implement stacks in Python. For example:

stack = []
stack.append(1)  # 压入元素1
stack.append(2)  # 压入元素2
print(stack.pop())  # 弹出栈顶元素2
print(stack[-1])  # 输出栈顶元素1

7. Queue
Queue is a data structure with First In First Out (FIFO) characteristics. Common operations on queues include enqueue, dequeue, and front. Queues can be implemented in Python using lists and deque in the collections module. For example:

from collections import deque
queue = deque()
queue.append(1)  # 入队元素1
queue.append(2)  # 入队元素2
print(queue.popleft())  # 出队元素1
print(queue[0])  # 输出队首元素2

8. Heap A
heap is a data structure that can quickly find the largest or smallest element. The heap can be implemented in Python using the heapq module. For example:

import heapq
heap = []
heapq.heappush(heap, 3)  # 将3压入堆中
heapq.heappush(heap, 1)  # 将1压入堆中
heapq.heappush(heap, 4)  # 将4压入堆中
print(heapq.heappop(heap))  # 弹出最小元素1
print(heapq.heappop(heap))  # 弹出次小元素3

9. Tree
A tree is a non-linear data structure consisting of nodes and edges, and each node can have zero or more child nodes. Trees have many important concepts and properties, including root nodes, leaf nodes, depth, height, parent nodes, child nodes, sibling nodes, etc. Trees can be implemented in Python using classes and objects. For example:

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)

10. Graph
A graph is a complex data structure composed of nodes and edges. The difference between it and a tree is that a graph can have cycles and multiple connected components. Graphs have many important concepts and properties, including vertices, edges, weights, degrees, connectivity, shortest paths, minimum spanning trees, etc. Graphs can be implemented in Python using dictionaries and classes. For example:

graph = {
    'A': ['B', 'C'],
    'B': ['C', 'D'],
    'C': ['D'],
    'D': ['C'],
    'E': ['F'],
    'F': ['C']
}

In this article, we introduced common data structures in Python, including lists, tuples, dictionaries, sets, strings, stacks, queues, heaps, trees, and graphs. Each data structure has its own special purpose and implementation, and understanding their advantages and disadvantages can help us choose the appropriate data structure when writing code. At the same time, we also introduced some modules and classes in Python, which provide some ready-made data structure implementations and algorithm implementations.

Learning data structures and algorithms is a very important part of programming, it can help us write more efficient and elegant code. Python provides many convenient data structures and algorithm implementations, and we can choose and use them flexibly. Understanding the advantages and disadvantages of data structures can help us better understand how they work and where they are applicable, and choosing an appropriate data structure can help us optimize code efficiency and maintainability.

Guess you like

Origin blog.csdn.net/naer_chongya/article/details/131248944