(四)Python基础入门-核心数据结构

概览

  • 列表操作(增删改查/切片/推导式)
  • 元组特性与不可变性
  • 字典操作(键值对/嵌套字典)
  • 集合运算(交集/并集/差集)

Python的核心数据结构是编程的基石,本文将系统讲解列表、元组、字典和集合四大数据结构,包含详细的教学内容和实用示例。

一、列表:灵活的可变序列

列表是Python中最常用的数据结构,支持存储不同类型元素,并允许动态修改。

创建与基本操作

py 复制代码
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 3.14, True]  # 支持混合类型

# 索引访问(正向从0开始,负向从-1开始)
print(fruits[0])   # "apple"
print(fruits[-1])  # "cherry"

# 添加元素
fruits.append("orange")       # 末尾添加 ["apple", "banana", "cherry", "orange"]
fruits.insert(1, "mango")     # 指定位置插入 ["apple", "mango", "banana", "cherry", "orange"]

# 删除元素
fruits.remove("banana")       # 按值删除
popped = fruits.pop(2)        # 按索引删除并返回被删元素
del fruits[0:2]               # 删除切片 ["cherry", "orange"]

# 修改元素
fruits[0] = "kiwi"            # 直接赋值修改

切片操作详解

切片语法:

list[start:stop:step]

py 复制代码
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 基础切片
print(numbers[2:5])    # [2, 3, 4]  索引2到5(不含5)
print(numbers[:3])     # [0, 1, 2]  从头开始
print(numbers[7:])     # [7, 8, 9]  直到末尾

# 步长切片
print(numbers[::2])    # [0, 2, 4, 6, 8]  每隔一个取
print(numbers[1::2])   # [1, 3, 5, 7, 9]  奇数索引
print(numbers[::-1])   # [9, 8, 7, ...]   逆序列表

# 切片复制
copy = numbers[:]      # 创建全新列表副本

列表推导式实战

列表推导式提供简洁高效的创建方式:

py 复制代码
# 基础推导式
squares = [x**2 for x in range(10)]  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 条件过滤
even_squares = [x**2 for x in range(10) if x % 2 == 0]  # [0, 4, 16, 36, 64]

# 嵌套推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 带条件转换
grades = [85, 92, 78, 90, 65]
result = ["Pass" if score >= 70 else "Fail" for score in grades]  # ['Pass', 'Pass', 'Pass', 'Pass', 'Fail']

二、元组:不可变的守护者

元组与列表类似,但创建后不可修改,适合存储不应改变的数据。

创建与特性

py 复制代码
# 创建元组
colors = ("red", "green", "blue")
coordinates = (40.7128, -74.0060)  # 经纬度数据

# 单元素元组需加逗号
single = ("only",)  # 注意逗号
not_tuple = ("oops")  # 这实际是字符串

# 解包赋值
x, y, z = colors  # x="red", y="green", z="blue"

# 不可变性验证
try:
    colors[1] = "yellow"  # 尝试修改
except TypeError as e:
    print(f"错误:{e}")  # 'tuple' object does not support item assignment

元组的实际应用场景

py 复制代码
# 1. 函数返回多个值
def get_dimensions():
    return 1920, 1080

width, height = get_dimensions()

# 2. 字典键值(列表不能作为键)
locations = {
    (35.6895, 139.6917): "Tokyo",
    (40.7128, -74.0060): "New York"
}

# 3. 保护重要数据
CONFIG = ("admin", "secure_password", 8080)
# 后续无法修改CONFIG内容

# 4. 格式化字符串
print("%s 的坐标是 (%.2f, %.2f)" % ("东京", 35.68, 139.69))

元组vs列表性能对比

py 复制代码
import sys
import timeit

list_size = sys.getsizeof([1, 2, 3, 4, 5])  # 112 bytes
tuple_size = sys.getsizeof((1, 2, 3, 4, 5))  # 88 bytes

list_time = timeit.timeit("x = [1, 2, 3, 4, 5]", number=1000000)  # 约0.06秒
tuple_time = timeit.timeit("x = (1, 2, 3, 4, 5)", number=1000000) # 约0.02秒

三、字典:高效的键值映射

字典通过哈希表实现,具有O(1)时间复杂度的查找效率。

基础操作详解

py 复制代码
# 创建字典
student = {
    "name": "Alice",
    "age": 20,
    "courses": ["Math", "Physics"]
}

# 增/改元素
student["email"] = "alice@example.com"  # 新增
student["age"] = 21  # 修改

# 删除元素
del student["courses"]  # 删除键值对
age = student.pop("age")  # 删除并返回值

# 查询元素
print(student["name"])  # 直接访问(键不存在会报错)
print(student.get("phone", "N/A"))  # 安全访问,不存在返回默认值

# 遍历字典
for key in student:  # 遍历键
    print(key)
    
for key, value in student.items():  # 同时遍历键值
    print(f"{key}: {value}")

嵌套字典实战

py 复制代码
# 多层嵌套结构
university = {
    "departments": {
        "CS": {
            "head": "Dr. Smith",
            "courses": ["Algorithms", "AI"]
        },
        "Math": {
            "head": "Dr. Johnson",
            "courses": ["Calculus", "Statistics"]
        }
    },
    "students": 15000
}

# 访问嵌套值
print(university["departments"]["CS"]["courses"][0])  # "Algorithms"

# 修改嵌套值
university["departments"]["Math"]["head"] = "Dr. Brown"

# 添加新系
university["departments"]["Physics"] = {
    "head": "Dr. Wilson",
    "courses": ["Mechanics", "Quantum Physics"]
}

# 安全访问深层次键
from collections import defaultdict
grades = defaultdict(lambda: "N/A", {"Math": "A", "Physics": "B"})
print(grades["Chemistry"])  # 输出 "N/A" 而不报错

字典推导式

py 复制代码
# 基本推导式
numbers = [1, 2, 3, 4]
squares = {x: x**2 for x in numbers}  # {1: 1, 2: 4, 3: 9, 4: 16}

# 条件过滤
even_squares = {x: x**2 for x in numbers if x % 2 == 0}  # {2: 4, 4: 16}

# 键值转换
student = {"name": "Alice", "age": 20}
uppercase = {key.upper(): str(value).upper() for key, value in student.items()}  # {"NAME": "ALICE", "AGE": "20"}

四、集合:无序且唯一

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

基本操作

py 复制代码
# 创建集合
primes = {2, 3, 5, 7, 11}
evens = set([2, 4, 6, 8, 10])

# 添加元素
primes.add(13)    # {2, 3, 5, 7, 11, 13}
primes.add(3)     # 重复元素自动忽略

# 删除元素
primes.remove(2)  # 删除存在的元素
primes.discard(4) # 安全删除(元素不存在不报错)

# 集合运算
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A | B)  # 并集 {1, 2, 3, 4, 5, 6}
print(A & B)  # 交集 {3, 4}
print(A - B)  # 差集 {1, 2}
print(A ^ B)  # 对称差 {1, 2, 5, 6}

# 成员测试(O(1)时间复杂度)
if 5 in B:
    print("5在集合B中")

集合实际应用

py 复制代码
# 1. 数据去重
words = ["hello", "world", "hello", "python", "world"]
unique_words = set(words)  # {"hello", "world", "python"}

# 2. 关系测试
developers = {"Alice", "Bob", "Charlie"}
designers = {"Bob", "David", "Eve"}
both_roles = developers & designers  # {"Bob"}

# 3. 过滤重复内容
emails = ["a@test.com", "b@test.com", "a@test.com", "c@test.com"]
unique_emails = list(set(emails))  # 去重后转回列表

# 4. 大型数据成员测试(效率远高于列表)
big_set = set(range(1000000))
%timeit 999999 in big_set  # 约 0.03 毫秒

big_list = list(range(1000000))
%timeit 999999 in big_list # 约 12 毫秒

数据结构对比与选型指南

特性 列表(List) 元组(Tuple) 字典(Dict) 集合(Set)
可变性 可变 不可变 可变 可变
排序 有序 有序 无序(Python3.7+有序) 无序
元素特性 可重复 可重复 键唯一 元素唯一
查找速度 O(n) O(n) O(1) O(1)
内存占用 中等 较小 较大 较大
典型应用 同质数据序列 数据保护/常量 键值映射 去重/集合运算

选型决策树:

  1. 需要修改元素? → 列表(有序数据)/字典(键值对)
  2. 需要保护数据不被修改? → 元组
  3. 需要快速查找元素? → 字典(按键查找)/集合(按值查找)
  4. 需要去重? → 集合
  5. 需要数学集合运算? → 集合

最佳实践建议:

  1. 使用元组存储不应更改的数据(如配置常量)
  2. 优先选择字典进行键值映射,特别是大型数据集
  3. 使用集合推导式比循环更高效
  4. 切片操作时注意:start包含,end不包含
  5. 字典键必须为不可变类型(字符串、数字、元组)

掌握这些核心数据结构及其特性,能够根据具体需求选择最合适的工具,大幅提升代码效率和可读性。

本文由元来智联开发团队出品:元来智联-网站、小程序等定制开发,专业开发服务商