常见的数据结构及其案例

以下将为你介绍 Python 中常见的数据结构,包括列表(List)、元组(Tuple)、集合(Set)、字典(Dictionary)、栈(Stack)、队列(Queue)和链表(Linked List),并给出相应的案例代码。

1. 列表(List)

列表是 Python 中最常用的数据结构之一,它是可变的、有序的,可以存储不同类型的元素。

案例:计算列表中所有元素的和

# 定义一个包含整数的列表
numbers = [1, 2, 3, 4, 5]
# 初始化总和为 0
total = 0
# 遍历列表中的每个元素
for num in numbers:
    total = total + num
print("列表中所有元素的和为:", total)

# 也可以使用 Python 内置的 sum 函数
sum_result = sum(numbers)
print("使用 sum 函数计算的和为:", sum_result)

2. 元组(Tuple)

元组是不可变的、有序的,通常用于存储一组不可修改的数据。

案例:统计元组中某个元素的出现次数

# 定义一个元组
fruits = ('apple', 'banana', 'apple', 'cherry')
# 统计 'apple' 在元组中出现的次数
count = fruits.count('apple')
print("'apple' 在元组中出现的次数为:", count)

3. 集合(Set)

集合是无序的、唯一的,常用于去重和成员检测。

案例:找出两个集合的交集

# 定义两个集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 计算两个集合的交集
intersection = set1.intersection(set2)
print("两个集合的交集为:", intersection)

4. 字典(Dictionary)

字典是无序的键值对集合,通过键来访问值。

案例:统计字符串中每个字符的出现次数

# 定义一个字符串
string = "hello"
# 初始化一个空字典
char_count = {}
# 遍历字符串中的每个字符
for char in string:
    if char in char_count:
        char_count[char] = char_count[char] + 1
    else:
        char_count[char] = 1
print("每个字符的出现次数为:", char_count)

5. 栈(Stack)

栈是一种后进先出(LIFO)的数据结构,可以使用列表来实现。

案例:使用栈实现括号匹配

def is_matching_pair(left, right):
    if left == '(' and right == ')':
        return True
    if left == '[' and right == ']':
        return True
    if left == '{' and right == '}':
        return True
    return False


def is_balanced(expression):
    stack = []
    for char in expression:
        if char in '([{':
            stack.append(char)
        elif char in ')]}':
            if not stack:
                return False
            top = stack.pop()
            if not is_matching_pair(top, char):
                return False
    return len(stack) == 0


expression = "{[()]}"
print("括号是否匹配:", is_balanced(expression))

6. 队列(Queue)

队列是一种先进先出(FIFO)的数据结构,可以使用 collections 模块中的 deque 来实现。

案例:使用队列实现广度优先搜索(BFS)

from collections import deque

# 定义图的邻接表
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E']
}


def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)

    while queue:
        vertex = queue.popleft()
        print(vertex, end=' ')
        for neighbor in graph[vertex]:
            if neighbor not in visited:
                queue.append(neighbor)
                visited.add(neighbor)


print("广度优先搜索结果:")
bfs(graph, 'A')

7. 链表(Linked List)

链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。

案例:实现一个简单的单向链表

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 display(self):
        elements = []
        current_node = self.head
        while current_node:
            elements.append(current_node.data)
            current_node = current_node.next
        print(" -> ".join(map(str, elements)))


# 创建一个链表并添加元素
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
# 显示链表中的元素
llist.display()

这些案例展示了不同数据结构的基本用法和常见应用场景,有助于你更好地理解和使用它们。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值