A must-read guide for getting started with Python’s basic data structures

Get more information

Author's homepage: Brother Tao talks about Python

Personal website: Brother Tao talks about Python


Hello everyone, I am Brother Tao. Today I will share with you common data structures in Python.

1.Array

Meaning: An array is an ordered data structure in which elements can be accessed by index. The size of an array is usually fixed and cannot be changed once created.

Basic operations:

# 创建数组
arr = [1, 2, 3, 4, 5]

# 访问元素
element = arr[2]  # 获取第三个元素,索引从0开始

# 修改元素
arr[1] = 6

# 获取数组长度
length = len(arr)

# 迭代数组
for item in arr:
    print(item)

2. List

Meaning: A list is a built-in data structure in Python. It is an ordered mutable sequence that can store elements of different types.

Basic operations:

# 创建列表
my_list = [1, 2, 3, "hello"]

# 添加元素
my_list.append(4)  # 添加元素到末尾
my_list.insert(2, 5)  # 在指定位置插入元素

# 删除元素
my_list.remove(3)  # 移除指定元素
popped_item = my_list.pop()  # 移除并返回末尾元素

# 获取列表长度
length = len(my_list)

# 列表切片
subset = my_list[1:3]  # 获取索引1到2的子列表

3.Stack

Meaning: The stack is a last-in-first-out (LIFO) data structure, and insertion and deletion operations can only be performed on the top of the stack.

Basic operations:

# 创建空栈
stack = []

# 入栈
stack.append(1)
stack.append(2)

# 出栈
popped_item = stack.pop()

# 获取栈顶元素
top_item = stack[-1]

# 检查栈是否为空
is_empty = len(stack) == 0

4.Queue

Meaning: The queue is a first-in-first-out (FIFO) data structure. Insertion operations can only be performed at one end of the queue, and deletion operations can be performed at the other end.

Basic operations:

from collections import deque

# 创建空队列
queue = deque()

# 入队
queue.append(1)
queue.append(2)

# 出队
popped_item = queue.popleft()

# 获取队列头元素
front_item = queue[0]

# 检查队列是否为空
is_empty = len(queue) == 0

5. Linked list

Meaning: A linked list is a dynamic data structure consisting of nodes, each node contains a data element and a reference to the next node. A linked list can be a singly linked list, a doubly linked list or a circular linked list.

Basic operations:

class ListNode:
    def __init__(self, value):
        self.value = value
        self.next = None

# 创建链表节点
node1 = ListNode(1)
node2 = ListNode(2)

# 构建链表
node1.next = node2

# 遍历链表
current = node1
while current:
    print(current.value)
    current = current.next

6. Hash table (dictionary)

Meaning: A hash table is a key-value pair storage structure that maps keys to specific storage locations through a hash function to achieve fast lookup and insertion operations.

Basic operations:

# 创建空字典
my_dict = {
    
    }

# 添加键值对
my_dict["name"] = "Alice"
my_dict["age"] = 30

# 获取值
value = my_dict["name"]

# 删除键值对
del my_dict["age"]

# 检查键是否存在
key_exists = "name" in my_dict

7.Tree

Meaning: A tree is a hierarchical data structure consisting of nodes, each node can have zero or more child nodes. Trees are often used to represent hierarchical relationships, such as file systems, organizational structures, etc.

Basic operations: Basic tree operations include node insertion, deletion and traversal.

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

# 创建树节点
root = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)

# 构建树结构
root.left = node2
root.right = node3

# 遍历树(例如中序遍历)
def inorder_traversal(node):
    if node:
        inorder_traversal(node.left)
        print(node.value)
        inorder_traversal(node.right)

inorder_traversal(root)

8. Figure

Meaning: A graph is a data structure that represents relationships between objects and consists of nodes (vertices) and edges. Graphs can be directed or undirected and can be used to represent complex structures such as networks and social relationships.

Basic operations: The basic operations of the graph include adding and deleting nodes and adding and deleting edges. Graph traversal operations can include depth-first search (DFS) and breadth-first search (BFS).

class Graph:
    def __init__(self):
        self.graph = {
    
    }

    def add_node(self, node):
        if node not in self.graph:
            self.graph[node] = []

    def add_edge(self, node1, node2):
        self.graph[node1].append(node2)
        self.graph[node2].append(node1)

# 创建图
my_graph = Graph()
my_graph.add_node("A")
my_graph.add_node("B")
my_graph.add_edge("A", "B")

# 图的遍历示例
def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    print(start, end=' ')
    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited)

print("深度优先搜索结果:")
dfs(my_graph.graph, "A")

That’s it for today’s sharing.


at last

If you want to get more and richer materials, you can click on the business card below the article and reply [ Quality Materials ] to get a comprehensive learning information package.
Insert image description here

How to obtain information:

If you are eager to get more valuable information about Python programming, you may wish to visit my personal homepage. There, you'll find more in-depth Python tutorials, useful tools, project examples, professional advice, and more.
Click on the link card below the article, reply [ Quality Information ], and you can directly receive the information gift package.

Guess you like

Origin blog.csdn.net/wuShiJingZuo/article/details/133013422