网站首页 > 技术文章 正文
在 Python 中,数据类型可分为可变类型(如列表、字典、集合)和不可变类型(如字符串、元组、数值)。下面针对不同数据类型详细讲解其增删改查操作,并给出代码示例、输出结果及分析总结。
1. 列表(List):有序可变序列
python
# 初始化列表
my_list = [1, 2, 3, 'hello', 'world']
# 增:添加元素
my_list.append('new') # 在末尾添加
my_list.insert(2, 'inserted') # 在索引2处插入
print("添加后:", my_list)
# 输出:
# [1, 2, 'inserted', 3, 'hello', 'world', 'new']
# 删:删除元素
my_list.remove('hello') # 删除指定值
del my_list[1] # 删除索引1的元素
print("删除后:", my_list)
# 输出:
# [1, 'inserted', 3, 'world', 'new']
# 改:修改元素
my_list[0] = 100 # 修改索引0的元素
print("修改后:", my_list)
# 输出:
# [100, 'inserted', 3, 'world', 'new']
# 查:访问元素
print("索引2的元素:", my_list[2])
# 输出:
# 3
print("元素是否存在:", 'world' in my_list)
# 输出:
# True
2. 字典(Dict):键值对映射
python
# 初始化字典
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 增:添加键值对
my_dict['job'] = 'Engineer'
print("添加后:", my_dict)
# 输出:
# {'name': 'Alice', 'age': 25, 'city': 'New York', 'job': 'Engineer'}
# 删:删除键值对
del my_dict['age']
print("删除后:", my_dict)
# 输出:
# {'name': 'Alice', 'city': 'New York', 'job': 'Engineer'}
# 改:修改值
my_dict['name'] = 'Bob'
print("修改后:", my_dict)
# 输出:
# {'name': 'Bob', 'city': 'New York', 'job': 'Engineer'}
# 查:访问值
print("name的值:", my_dict['name'])
# 输出:
# Bob
print("所有键:", my_dict.keys())
# 输出:
# dict_keys(['name', 'city', 'job'])
print("所有值:", my_dict.values())
# 输出:
# dict_values(['Bob', 'New York', 'Engineer'])
3. 集合(Set):无序不重复元素
python
# 初始化集合(自动去重)
my_set = {1, 2, 3, 3, 4}
print("初始化后:", my_set)
# 输出:
# {1, 2, 3, 4}
# 增:添加元素
my_set.add(5)
my_set.update([6, 7])
print("添加后:", my_set)
# 输出:
# {1, 2, 3, 4, 5, 6, 7}
# 删:删除元素
my_set.remove(3)
my_set.discard(5)
print("删除后:", my_set)
# 输出:
# {1, 2, 4, 6, 7}
# 查:检查元素是否存在
print("元素是否存在:", 4 in my_set)
# 输出:
# True
# 集合运算
other_set = {4, 5, 6}
print("交集:", my_set & other_set)
# 输出:
# {4, 6}
print("并集:", my_set | other_set)
# 输出:
# {1, 2, 4, 5, 6, 7}
4. 字符串(Str):不可变字符序列
python
# 初始化字符串
my_str = "Hello, World!"
# 增:拼接字符串(生成新字符串)
new_str = my_str + " Welcome"
print("拼接后:", new_str)
# 输出:
# Hello, World! Welcome
# 改:替换字符(生成新字符串)
replaced = new_str.replace("World", "Python")
print("替换后:", replaced)
# 输出:
# Hello, Python! Welcome
# 查:访问字符和子串
print("索引6的字符:", replaced[6])
# 输出:
# P
print("子串位置:", replaced.find("Python"))
# 输出:
# 7
print("是否包含子串:", "Welcome" in replaced)
# 输出:
# True
5. 元组(Tuple):有序不可变序列
python
# 初始化元组
my_tuple = (1, 2, 'hello', [3, 4])
# 查:访问元素
print("索引2的元素:", my_tuple[2])
# 输出:
# hello
# 注意:元组不可变,但内部可变元素可修改
my_tuple[3][0] = 100 # 修改元组内列表的元素
print("修改后:", my_tuple)
# 输出:
# (1, 2, 'hello', [100, 4])
6. 数值类型(int/float/complex):不可变数值
python
# 初始化数值
num_int = 10
num_float = 3.14
num_complex = 2 + 3j
# 改:重新赋值(生成新对象)
num_int = num_int + 5
print("修改后:", num_int)
# 输出:
# 15
# 查:数值运算
print("整数加法:", 5 + 3)
# 输出:
# 8
print("浮点数乘法:", num_float * 2)
# 输出:
# 6.28
print("复数实部:", num_complex.real)
# 输出:
# 2.0
7. 多维数据结构示例
python
# 嵌套列表(二维数组)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 访问第二行第三列元素
print("矩阵元素:", matrix[1][2])
# 输出:
# 6
# 修改元素
matrix[0][0] = 100
print("修改后矩阵:", matrix)
# 输出:
# [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
# 嵌套字典
student = {
"name": "Alice",
"age": 20,
"scores": {
"math": 90,
"english": 85,
"science": 95
}
}
# 访问嵌套值
print("数学成绩:", student["scores"]["math"])
# 输出:
# 90
# 添加新科目
student["scores"]["history"] = 88
print("更新后成绩:", student["scores"])
# 输出:
# {'math': 90, 'english': 85, 'science': 95, 'history': 88}
8. 特殊数据类型操作
8.1 冻结集合(FrozenSet):不可变集合
python
# 初始化冻结集合
frozen = frozenset([1, 2, 3])
# 查:检查元素
print("元素是否存在:", 2 in frozen)
# 输出:
# True
# 注意:冻结集合不可修改
# frozen.add(4) # 报错:'frozenset' object has no attribute 'add'
8.2 命名元组(NamedTuple):带字段名的元组
python
from collections import namedtuple
# 定义命名元组
Point = namedtuple('Point', ['x', 'y'])
# 创建实例
p = Point(10, 20)
# 访问元素
print("x坐标:", p.x)
# 输出:
# 10
print("y坐标:", p[1])
# 输出:
# 20
分析总结
数据类型 | 特点 | 增删改查方式 | 适用场景 |
列表 | 有序、可变、可重复 | 索引操作、append/insert/remove/del | 动态数据存储、需要保留顺序 |
字典 | 键值对、无序、键唯一 | 键操作、update/pop | 快速查找、配置数据 |
集合 | 无序、不可重复 | add/update/remove/discard | 去重、集合运算 |
字符串 | 不可变、字符序列 | 拼接 / 替换(生成新字符串) | 文本处理、格式化 |
元组 | 有序、不可变 | 只能查询 | 固定数据、函数返回多值 |
数值 | 不可变 | 重新赋值 | 数学计算 |
冻结集合 | 不可变、无序、唯一 | 只能查询 | 作为字典键、集合元素 |
命名元组 | 不可变、带字段名 | 通过字段名或索引查询 | 轻量级对象、数据传输 |
关键要点:
- 不可变类型(如字符串、元组、数值、冻结集合)修改时需创建新对象,适合需要数据安全的场景。
- 可变类型(如列表、字典、集合)支持原地修改,适合动态操作。
- 嵌套结构(如多维列表、嵌套字典)可表示复杂数据关系,操作时需注意层级访问。
- 特殊类型(如命名元组、冻结集合)提供了更精确的数据建模能力,减少代码歧义。
选择合适的数据类型能显著提升代码效率和可读性,建议根据数据特性和操作需求灵活使用。
猜你喜欢
- 2025-06-15 python入门到脱坑函数—语法详解(python函数教程)
- 2025-06-15 python中的流程控制语句:continue、break 和 return使用方法
- 2025-06-15 在Python中将函数作为参数传入另一个函数中
- 2025-06-15 Python:读取文本返回关键词及其权重
- 2025-06-15 Python学不会来打我(21)python表达式知识点汇总
- 2025-06-15 Python基础入门之range()函数用方法详解
- 2025-06-15 python入门 到脱坑输入与输出—str()函数与repr()函数
- 2025-06-15 Python教程:序列中的最大值max()、最小值min()和长度len()详解
- 2025-06-15 Python学不会来打我(20)循环控制语句break/continue详解
- 2025-06-15 第九章:Python文件操作与输入输出
- 06-15python 打地鼠小游戏(打地鼠小游戏代码)
- 06-15浅析 Python 中的队列类(python队列函数)
- 06-15python委托定制超类getattr和getattribute管理属性
- 06-15python 内置函数 getattr(python内置函数的用法)
- 06-15一文掌握Python 的 getattr函数(python中getattribute)
- 06-15Python 字典 get() 方法:操作指南
- 06-15python入门到脱坑函数—语法详解(python函数教程)
- 06-15python中的流程控制语句:continue、break 和 return使用方法
- 266℃Python短文,Python中的嵌套条件语句(六)
- 265℃python笔记:for循环嵌套。end=""的作用,图形打印
- 264℃PythonNet:实现Python与.Net代码相互调用!
- 259℃Python实现字符串小写转大写并写入文件
- 258℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 118℃原来2025是完美的平方年,一起探索六种平方的算吧
- 99℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 92℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
-
- python 打地鼠小游戏(打地鼠小游戏代码)
- 浅析 Python 中的队列类(python队列函数)
- python委托定制超类getattr和getattribute管理属性
- python 内置函数 getattr(python内置函数的用法)
- 一文掌握Python 的 getattr函数(python中getattribute)
- Python 字典 get() 方法:操作指南
- python入门到脱坑函数—语法详解(python函数教程)
- python中的流程控制语句:continue、break 和 return使用方法
- 在Python中将函数作为参数传入另一个函数中
- Python:读取文本返回关键词及其权重
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)