当前位置: 首页> 教育> 幼教 > 【30天玩转python】高级数据结构

【30天玩转python】高级数据结构

时间:2025/8/25 12:57:29来源:https://blog.csdn.net/weixin_39372311/article/details/142243581 浏览次数:0次

高级数据结构

在 Python 中,除了基础的列表、元组、字典和集合等数据结构之外,还有一些更复杂和高级的数据结构。这些数据结构在解决特定问题时能够提供更好的性能和更强的功能。本节将介绍一些常用的高级数据结构,包括堆、队列、双端队列、链表、树、图等,了解它们的基本概念以及在 Python 中的实现方式。


1. 堆(Heap)

堆是一种特殊的树形数据结构,满足堆属性。堆可以分为最小堆最大堆,最小堆中父节点的值总是小于或等于子节点,而最大堆中父节点的值总是大于或等于子节点。

在 Python 中,heapq 模块提供了堆的实现,默认是最小堆。

1.1 使用 heapq 模块
import heapq# 创建一个最小堆
heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 1)
heapq.heappush(heap, 5)print(heap)  # 输出:[1, 10, 5]# 弹出最小元素
min_element = heapq.heappop(heap)
print(min_element)  # 输出:1
1.2 堆排序

利用堆的性质可以实现高效的排序。

def heap_sort(arr):heap = []for element in arr:heapq.heappush(heap, element)return [heapq.heappop(heap) for _ in range(len(heap))]arr = [3, 1, 4, 1, 5, 9]
sorted_arr = heap_sort(arr)
print(sorted_arr)  # 输出:[1, 1, 3, 4, 5, 9]

2. 队列(Queue)

队列是一种先进先出(FIFO)的数据结构,最先加入的元素最先被移出。在 Python 中,可以使用 collections.deque 实现队列,也可以使用 queue.Queue 实现线程安全的队列。

2.1 使用 collections.deque
from collections import dequequeue = deque([1, 2, 3])
queue.append(4)  # 入队
print(queue)  # 输出:deque([1, 2, 3, 4])queue.popleft()  # 出队
print(queue)  # 输出:deque([2, 3, 4])
2.2 使用 queue.Queue
from queue import Queueq = Queue()
q.put(1)  # 入队
q.put(2)
q.put(3)print(q.get())  # 出队,输出:1
print(q.get())  # 输出:2

3. 双端队列(Deque)

双端队列(Deque)是可以在两端进行插入和删除的队列。在 Python 中,可以使用 collections.deque 来实现双端队列。

from collections import dequedq = deque([1, 2, 3])
dq.append(4)       # 从右端插入
dq.appendleft(0)   # 从左端插入
print(dq)          # 输出:deque([0, 1, 2, 3, 4])dq.pop()           # 从右端删除
dq.popleft()       # 从左端删除
print(dq)          # 输出:deque([1, 2, 3])

4. 链表(Linked List)

链表是一种线性数据结构,由多个节点组成。每个节点包含两部分:数据和指向下一个节点的引用。链表的优势是插入和删除元素非常高效,尤其是与数组相比。

4.1 单链表的实现
class Node:def __init__(self, data):self.data = dataself.next = Noneclass LinkedList:def __init__(self):self.head = Nonedef append(self, data):new_node = Node(data)if not self.head:self.head = new_nodereturnlast_node = self.headwhile last_node.next:last_node = last_node.nextlast_node.next = new_nodedef print_list(self):current = self.headwhile current:print(current.data, end=" -> ")current = current.nextprint("None")# 使用链表
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.print_list()  # 输出:1 -> 2 -> 3 -> None

5. 树(Tree)

树是一种层次型的数据结构,由节点组成,通常包括一个根节点和若干子节点。树的常见类型有二叉树、二叉搜索树、平衡树等。

5.1 二叉树的实现
class TreeNode:def __init__(self, data):self.data = dataself.left = Noneself.right = None# 创建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)# 前序遍历
def preorder_traversal(node):if node:print(node.data, end=" ")preorder_traversal(node.left)preorder_traversal(node.right)preorder_traversal(root)  # 输出:1 2 4 5 3

6. 图(Graph)

图是由顶点和边组成的复杂数据结构,图可以是有向图或无向图,也可以是带权图。常用的表示方法包括邻接矩阵和邻接表。

6.1 使用邻接表表示图
class Graph:def __init__(self):self.graph = {}def add_edge(self, u, v):if u not in self.graph:self.graph[u] = []self.graph[u].append(v)def print_graph(self):for node in self.graph:print(f"{node} -> {self.graph[node]}")# 创建图
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)g.print_graph()
# 输出:
# 0 -> [1, 2]
# 1 -> [2]
# 2 -> [0, 3]

7. 哈希表(Hash Table)

哈希表是一种基于键值对的数据结构,使用哈希函数将键映射到对应的值。Python 中的字典(dict)实际上是哈希表的实现。

7.1 使用字典
hash_table = {}
hash_table["name"] = "Alice"
hash_table["age"] = 25print(hash_table)  # 输出:{'name': 'Alice', 'age': 25}
print(hash_table["name"])  # 输出:Alice

8. 小结

高级数据结构为复杂问题的解决提供了灵活高效的工具。通过理解堆、队列、双端队列、链表、树、图和哈希表的实现和使用,程序员可以选择适合的问题模型,并提高代码的性能和可扩展性。在不同的应用场景下,选择合适的数据结构至关重要。

关键字:【30天玩转python】高级数据结构

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: