Python3入门指南Python语言的特点和实际应用Python3环境搭建配置VSCode进行Python开发Python基础语法Python变量与数据类型Python数据类型转换Python解释器使用Python注释使用Python运算符Python数字类型Python字符串操作Python列表操作Python元组使用Python字典使用Python集合使用Python条件控制详解Python循环语句详解Python编程入门实践Python推导式详解Python迭代器和生成器Python with语句详解Python函数详解Python lambda(匿名函数)Python装饰器Python数据结构Python模块和包使用Python中__name__和__main__的用法Python输入输出:从基础到文件操作Python文件操作Python OS模块使用Python错误和异常处理Python面向对象编程Python命名空间和作用域Python虚拟环境:venv详细教程Python类型注解Python标准库常用模块Python正则表达式Python CGI编程Python MySQL(mysql-connector驱动)Python MySQL(PyMySQL驱动)Python网络编程Python发送邮件Python多线程编程Python XML解析Python JSON解析Python日期和时间处理Python操作MongoDBPython urllib库使用Python uWSGI 安装与配置Python pip包管理工具Python operator模块Python math模块Python requests模块HTTP请求Python random模块Python OpenAI库Python AI绘画制作Python statistics模块Python hashlib模块:哈希加密Python量化交易Python pyecharts数据可视化Python Selenium网页自动化Python BeautifulSoup网页数据提取Python Scrapy爬虫框架Python Markdown转HTMLPython sys模块Python Pickle模块:数据存储Python subprocess模块Python queue队列模块Python StringIO内存文件操作Python logging日志记录Python datetime日期时间处理Python re正则表达式Python csv表格数据处理Python threading 多线程编程Python asyncio 异步编程Python PyQt 图形界面开发Python 应用方向和常用库框架

Python数据结构

Python提供了多种强大的数据结构,这些结构能帮助我们高效地组织和处理数据。掌握这些数据结构的使用方法,对编写高质量的Python代码至关重要。


列表:最常用的可变序列

列表是Python中最灵活的数据结构之一。与字符串和元组不同,列表是可变的,这意味着我们可以修改列表中的内容。

列表常用方法

列表提供了丰富的方法来操作数据:

# 创建一个列表
fruits = ['apple', 'banana', 'orange']

# 添加元素
fruits.append('grape')        # 在末尾添加
fruits.insert(1, 'pear')      # 在指定位置插入

# 扩展列表
more_fruits = ['mango', 'pineapple']
fruits.extend(more_fruits)

# 删除元素
fruits.remove('banana')       # 删除指定元素
popped = fruits.pop(2)        # 删除并返回指定位置元素
last = fruits.pop()           # 删除并返回最后一个元素

# 查找和统计
index = fruits.index('apple') # 查找元素位置
count = fruits.count('apple') # 统计元素出现次数

# 排序和反转
fruits.sort()                 # 升序排序
fruits.reverse()              # 反转列表

# 清空列表
fruits.clear()

列表操作实例

让我们通过具体例子看看这些方法的使用:

numbers = [66.25, 333, 333, 1, 1234.5]

# 统计元素出现次数
print(numbers.count(333))     # 输出:2
print(numbers.count(66.25))   # 输出:1

# 插入元素
numbers.insert(2, -1)         # 在索引2位置插入-1
numbers.append(333)           # 在末尾添加333

# 查找元素位置
print(numbers.index(333))     # 输出:1

# 删除元素
numbers.remove(333)           # 删除第一个333

# 反转和排序
numbers.reverse()             # 反转列表
numbers.sort()                # 排序列表

print(numbers)                # 输出排序后的列表


用列表实现栈

栈是一种后进先出的数据结构,列表可以很方便地实现栈的功能。

基本栈操作

stack = []

# 压入元素(入栈)
stack.append(1)
stack.append(2)
stack.append(3)
print(stack)  # 输出:[1, 2, 3]

# 弹出元素(出栈)
top = stack.pop()
print(top)    # 输出:3
print(stack)  # 输出:[1, 2]

# 查看栈顶元素
peek = stack[-1]
print(peek)   # 输出:2

# 检查栈是否为空
is_empty = len(stack) == 0
print(is_empty)  # 输出:False

# 获取栈大小
size = len(stack)
print(size)   # 输出:2

完整的栈类实现

class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        """压入元素到栈顶"""
        self.items.append(item)
    
    def pop(self):
        """弹出栈顶元素"""
        if not self.is_empty():
            return self.items.pop()
        raise IndexError("从空栈弹出元素")
    
    def peek(self):
        """查看栈顶元素"""
        if not self.is_empty():
            return self.items[-1]
        raise IndexError("查看空栈")
    
    def is_empty(self):
        """检查栈是否为空"""
        return len(self.items) == 0
    
    def size(self):
        """返回栈的大小"""
        return len(self.items)

# 使用示例
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)

print(f"栈顶元素: {stack.peek()}")  # 输出:30
print(f"栈大小: {stack.size()}")     # 输出:3

print(f"弹出: {stack.pop()}")        # 输出:30
print(f"栈是否为空: {stack.is_empty()}")  # 输出:False


用列表实现队列

队列是先进先出的数据结构。虽然列表可以实现队列,但在处理大量数据时性能不佳。

使用列表实现队列

queue = []

# 入队
queue.append('A')
queue.append('B')
queue.append('C')
print(queue)  # 输出:['A', 'B', 'C']

# 出队
first = queue.pop(0)
print(first)  # 输出:A
print(queue)  # 输出:['B', 'C']

# 查看队首
front = queue[0]
print(front)  # 输出:B

使用deque实现高效队列

对于需要频繁进行队列操作的场景,建议使用collections.deque:

from collections import deque

# 创建队列
queue = deque()

# 入队
queue.append('A')
queue.append('B')
queue.append('C')

# 出队
first = queue.popleft()  # 比list.pop(0)更高效
print(first)  # 输出:A

# 查看队首
front = queue[0]
print(front)  # 输出:B


列表推导式

列表推导式提供了一种简洁创建列表的方法。

基本用法

# 将每个元素乘以3
numbers = [2, 4, 6]
tripled = [3 * x for x in numbers]
print(tripled)  # 输出:[6, 12, 18]

# 创建数字和平方的列表
squares = [[x, x**2] for x in numbers]
print(squares)  # 输出:[[2, 4], [4, 16], [6, 36]]

# 处理字符串
fruits = ['  banana', '  apple ', 'orange  ']
cleaned = [fruit.strip() for fruit in fruits]
print(cleaned)  # 输出:['banana', 'apple', 'orange']

带条件的列表推导式

numbers = [1, 2, 3, 4, 5, 6]

# 只保留大于3的数
filtered = [x for x in numbers if x > 3]
print(filtered)  # 输出:[4, 5, 6]

# 偶数乘以2,奇数保持不变
processed = [x * 2 if x % 2 == 0 else x for x in numbers]
print(processed)  # 输出:[1, 4, 3, 8, 5, 12]

多重循环

# 两个列表的元素相乘
list1 = [2, 4, 6]
list2 = [1, 2, 3]
result = [x * y for x in list1 for y in list2]
print(result)  # 输出:[2, 4, 6, 4, 8, 12, 6, 12, 18]

# 矩阵转置
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed)  # 输出:[[1, 4, 7], [2, 5, 8], [3, 6, 9]]


字典:键值对数据结构

字典是Python中非常重要的数据结构,用于存储键值对。

字典基本操作

# 创建字典
student = {'name': '小明', 'age': 20, 'grade': 'A'}

# 访问元素
print(student['name'])  # 输出:小明

# 添加或修改元素
student['age'] = 21
student['city'] = '北京'

# 删除元素
del student['grade']

# 检查键是否存在
if 'name' in student:
    print("姓名存在")

# 获取所有键和值
keys = student.keys()
values = student.values()

字典推导式

# 创建数字平方字典
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # 输出:{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 过滤字典
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in original.items() if v > 2}
print(filtered)  # 输出:{'c': 3, 'd': 4}


集合:无序不重复元素

集合用于存储不重复的元素,支持数学上的集合运算。

# 创建集合
fruits = {'apple', 'orange', 'banana', 'apple'}
print(fruits)  # 输出:{'orange', 'banana', 'apple'}(重复元素被去除)

# 集合运算
set1 = set('abracadabra')
set2 = set('alacazam')

print(set1 - set2)  # 差集:在set1中但不在set2中
print(set1 | set2)  # 并集:在set1或set2中
print(set1 & set2)  # 交集:在set1和set2中
print(set1 ^ set2)  # 对称差集:在set1或set2中,但不同时在两者中


遍历技巧

遍历字典

student_scores = {'小明': 85, '小红': 92, '小刚': 78}

for name, score in student_scores.items():
    print(f"{name}的成绩是{score}分")

使用enumerate获取索引

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

for index, fruit in enumerate(fruits):
    print(f"索引{index}的水果是{fruit}")

同时遍历多个序列

names = ['小明', '小红', '小刚']
scores = [85, 92, 78]
subjects = ['数学', '英语', '语文']

for name, score, subject in zip(names, scores, subjects):
    print(f"{name}的{subject}成绩是{score}分")

反向和排序遍历

numbers = [3, 1, 4, 1, 5, 9, 2]

# 反向遍历
for num in reversed(numbers):
    print(num)

# 排序遍历
for num in sorted(numbers):
    print(num)

# 去重后排序遍历
for num in sorted(set(numbers)):
    print(num)


实际应用建议

选择合适的数据结构

  • 列表:需要保持元素顺序,经常进行索引访问

  • 字典:需要通过键快速查找值

  • 集合:需要检查元素是否存在,或进行集合运算

  • 元组:数据不需要修改,用作字典键

性能考虑

  • 列表在开头插入/删除元素较慢(O(n))

  • deque在两端插入/删除都很快(O(1))

  • 集合的成员检查比列表快很多

代码可读性

使用合适的变量名和数据结构,让代码更易理解:

# 不好的写法
a = [1, 2, 3, 4, 5]

# 好的写法
student_scores = [85, 92, 78, 88, 95]

掌握这些数据结构的使用方法,能够让你写出更高效、更易维护的Python代码。在实际开发中,根据具体需求选择合适的数据结构非常重要。

本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/36_2097

目录选择