程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

小白必看!Python 六大数据类型增删改查秘籍,附超详细代码解析

hfteth 2025-06-15 16:26:12 技术文章 1 ℃

在 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

去重、集合运算

字符串

不可变、字符序列

拼接 / 替换(生成新字符串)

文本处理、格式化

元组

有序、不可变

只能查询

固定数据、函数返回多值

数值

不可变

重新赋值

数学计算

冻结集合

不可变、无序、唯一

只能查询

作为字典键、集合元素

命名元组

不可变、带字段名

通过字段名或索引查询

轻量级对象、数据传输

关键要点:

  1. 不可变类型(如字符串、元组、数值、冻结集合)修改时需创建新对象,适合需要数据安全的场景。
  2. 可变类型(如列表、字典、集合)支持原地修改,适合动态操作。
  3. 嵌套结构(如多维列表、嵌套字典)可表示复杂数据关系,操作时需注意层级访问。
  4. 特殊类型(如命名元组、冻结集合)提供了更精确的数据建模能力,减少代码歧义。

选择合适的数据类型能显著提升代码效率和可读性,建议根据数据特性和操作需求灵活使用。

最近发表
标签列表