【Python】数据结构有Python版吗?

李升伟 整理

数据结构可以用Python实现。Python提供了多种内置数据结构,如列表(list)、元组(tuple)、集合(set)、字典(dict)等。此外,Python的标准库还包含一些高级数据结构,如collections 模块中的dequedefaultdictCounter等。

以下是一些常见数据结构及其Python实现示例:

1. 数组/列表(List):

Python的列表类似于动态数组,可以存储不同类型的元素。

python 复制代码
my_list = [1, 2, 3, 4, 5]

2. 栈(Stack):

可以使用列表来实现栈,遵循后进先出(LIFO)原则。

python 复制代码
stack = []
stack.append(1)  # 入栈
stack.append(2)
stack.pop()      # 出栈,返回2

3. 队列(Queue):

可以使用collections.deque 来实现队列,遵循先进先出(FIFO)原则。

python 复制代码
from collections import deque
queue = deque()
queue.append(1)  # 入队
queue.append(2)
queue.popleft()  # 出队,返回1

4. 链表(Linked List):

可以自定义类来实现链表。

python 复制代码
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

    def print_list(self):
        current = self.head
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")

ll = LinkedList()
ll.append(1)
ll.append(2)
ll.print_list()  # 输出: 1 -> 2 -> None

5. 树(Tree):

可以自定义类来实现树结构。

python 复制代码
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.children = []

    def add_child(self, child):
        self.children.append(child)

root = TreeNode("A")
child1 = TreeNode("B")
child2 = TreeNode("C")
root.add_child(child1)
root.add_child(child2)

6. 图(Graph):

可以使用字典来实现图结构。

python 复制代码
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

7. 堆(Heap):

可以使用heapq模块来实现堆。

python 复制代码
import heapq

heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
heapq.heappop(heap)  # 返回1

8. 哈希表(Hash Table):

Python的字典(dict)就是基于哈希表实现的。

python 复制代码
hash_table = {}
hash_table['key1'] = 'value1'
hash_table['key2'] = 'value2'
print(hash_table['key1'])  # 输出: value1

这些是Python中实现常见数据结构的一些基本示例。根据具体需求,你可以进一步扩展和优化这些实现。

(来自deepseek问答。)

相关推荐
夏末之花24 分钟前
免费看付费电影网站制作,高清电影集合搜索引擎网站
python
想睡hhh37 分钟前
c语言数据结构——单向不带头不循环链表的实现
c语言·数据结构·链表
打不了嗝 ᥬ᭄1 小时前
平衡树的模拟实现
数据结构·c++
Python破壁人手记1 小时前
《我的Python觉醒之路》之转型Python(十三)——控制流
开发语言·python·神经网络·学习·机器学习
泽02021 小时前
数据结构之双向链表
数据结构
ChoSeitaku1 小时前
NO.42十六届蓝桥杯备战|数据结构|算法|时间复杂度|空间复杂度|STL(C++)
数据结构·算法·蓝桥杯
代码AC不AC1 小时前
【数据结构】顺序表(附源码)
c语言·数据结构·源码·顺序表·线性表
eqwaak01 小时前
实时数仓中的Pandas:基于Flink+Arrow的流式处理方案——毫秒级延迟下的混合计算新范式
大数据·分布式·python·学习·flink·pandas
带娃的IT创业者2 小时前
《Python实战进阶》No23: 使用 Selenium 自动化浏览器操作
python·selenium·自动化
钢铁男儿2 小时前
Python 生成数据(绘制简单的折线图)
开发语言·python·信息可视化