Python系列课(5)——数据容器

目录

一、数据容器入门

二、列表(list):重复有序

[1. 列表的定义](#1. 列表的定义)

[2. 列表的下标索引](#2. 列表的下标索引)

[3. 列表常用操作](#3. 列表常用操作)

[4. 列表的遍历](#4. 列表的遍历)

[5. 练习:取出列表内的偶数](#5. 练习:取出列表内的偶数)

三、元组(tuple):重复有序

[1. 元组的定义](#1. 元组的定义)

[2. 元组的操作](#2. 元组的操作)

[3. 元组的遍历](#3. 元组的遍历)

四、字符串(str):重复有序

[1. 字符串下标索引](#1. 字符串下标索引)

[2. 字符串常用操作](#2. 字符串常用操作)

[3. 练习:分割字符串](#3. 练习:分割字符串)

五、序列的切片

练习:字符串切片

六、集合(set):去重无序

[1. 集合的定义和特点](#1. 集合的定义和特点)

[2. 集合常用操作](#2. 集合常用操作)

[3. 集合的遍历](#3. 集合的遍历)

[4. 练习:列表去重](#4. 练习:列表去重)

七、字典(dict)

[1. 字典的定义](#1. 字典的定义)

[2. 字典的嵌套](#2. 字典的嵌套)

[3. 字典常用操作](#3. 字典常用操作)

[4. 练习:升职加薪](#4. 练习:升职加薪)

八、数据容器对比

[1. 分类对比](#1. 分类对比)

[2. 应用场景](#2. 应用场景)

九、数据容器通用操作

[1. 通用函数](#1. 通用函数)

[2. 类型转换](#2. 类型转换)

[3. 排序](#3. 排序)

十、数据容器速查表


一、数据容器入门

数据容器:一种可以容纳多份数据的数据类型,每一份数据称为一个元素。

Python有5种数据容器:

  • 列表(list)

  • 元组(tuple)

  • 字符串(str)

  • 集合(set)

  • 字典(dict)

复制代码
# 不使用数据容器(不高效)
name1 = "张三"
name2 = "李四"
name3 = "王五"
# ... 需要100个变量
​
# 使用数据容器(高效)
students = ["张三", "李四", "王五"]   # 列表
print(students)   # ['张三', '李四', '王五']

二、列表(list):重复有序

1. 列表的定义

复制代码
# 定义空列表
list1 = []
list2 = list()
print(list1)   # []
print(list2)   # []
​
# 定义带元素的列表
fruits = ["苹果", "香蕉", "橙子"]
print(fruits)   # ['苹果', '香蕉', '橙子']
​
# 混合类型列表
mixed = [1, "hello", 3.14, True]
print(mixed)   # [1, 'hello', 3.14, True]
​
# 嵌套列表
nested = [[1, 2], [3, 4], [5, 6]]
print(nested)   # [[1, 2], [3, 4], [5, 6]]

2. 列表的下标索引

复制代码
fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"]
​
# 正向索引(从0开始)
print(fruits[0])   # 苹果
print(fruits[2])   # 橙子
print(fruits[4])   # 西瓜
​
# 反向索引(从-1开始)
print(fruits[-1])   # 西瓜
print(fruits[-3])   # 橙子
​
# 嵌套列表索引
nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested[0][1])   # 2(第1个列表的第2个元素)
print(nested[2][0])   # 7(第3个列表的第1个元素)

3. 列表常用操作

复制代码
# 定义一个列表
my_list = [21, 25, 21, 23, 22, 20]
print(my_list)   # [21, 25, 21, 23, 22, 20]
​
# 1. 查找元素下标
index = my_list.index(25)
print(index)   # 1
​
# 2. 修改元素
my_list[2] = 99
print(my_list)   # [21, 25, 99, 23, 22, 20]
​
# 3. 插入元素
my_list.insert(2, 100)
print(my_list)   # [21, 25, 100, 99, 23, 22, 20]
​
# 4. 追加元素(尾部)
my_list.append(31)
print(my_list)   # [21, 25, 100, 99, 23, 22, 20, 31]
​
# 5. 扩展列表(追加另一个容器)
my_list.extend([29, 33, 30])
print(my_list)   # [21, 25, 100, 99, 23, 22, 20, 31, 29, 33, 30]
​
# 6. 删除元素(del)
del my_list[0]
print(my_list)   # [25, 100, 99, 23, 22, 20, 31, 29, 33, 30]
​
# 7. 删除元素(pop,返回被删除的元素)
removed = my_list.pop(0)
print(removed)   # 25
print(my_list)   # [100, 99, 23, 22, 20, 31, 29, 33, 30]
​
# 8. 删除指定值的第一个匹配项
my_list.remove(99)
print(my_list)   # [100, 23, 22, 20, 31, 29, 33, 30]
​
# 9. 清空列表
my_list.clear()
print(my_list)   # []
​
# 10. 统计某元素出现次数
score_list = [90, 85, 90, 78, 90]
count = score_list.count(90)
print(count)   # 3
​
# 11. 统计列表长度
print(len(score_list))   # 5

4. 列表的遍历

复制代码
# while循环遍历
print("while循环遍历:")
my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):
    print(my_list[i])
    i += 1
# 输出:
# 1
# 2
# 3
# 4
# 5
​
# for循环遍历
print("for循环遍历:")
for num in my_list:
    print(num)
# 输出:
# 1
# 2
# 3
# 4
# 5

5. 练习:取出列表内的偶数

复制代码
# 方法1:for循环
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = []
​
for num in my_list:
    if num % 2 == 0:
        even_list.append(num)
​
print(even_list)   # [2, 4, 6, 8, 10]
​
# 方法2:while循环
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = []
i = 0
​
while i < len(my_list):
    if my_list[i] % 2 == 0:
        even_list.append(my_list[i])
    i += 1
​
print(even_list)   # [2, 4, 6, 8, 10]

三、元组(tuple):重复有序

1. 元组的定义

复制代码
# 定义元组
t1 = (1, 2, 3)
print(t1)   # (1, 2, 3)
​
# 混合类型
t2 = (1, "hello", 3.14)
print(t2)   # (1, 'hello', 3.14)
​
# 定义单元素元组(需要加逗号)
t3 = (5,)
print(t3)   # (5,)
print(type(t3))   # <class 'tuple'>
​
# 不加逗号会变成整数
t4 = (5)
print(type(t4))   # <class 'int'>
​
# 嵌套元组
t5 = ((1, 2), (3, 4), (5, 6))
print(t5)   # ((1, 2), (3, 4), (5, 6))

2. 元组的操作

复制代码
# 定义元组
student = ('周杰轮', 11, ['football', 'music'])
print(student)   # ('周杰轮', 11, ['football', 'music'])
​
# 1. 查找元素下标
index = student.index(11)
print(index)   # 1
​
# 2. 统计元素个数
count = student.count('周杰轮')
print(count)   # 1
​
# 3. 获取长度
print(len(student))   # 3
​
# 4. 通过下标获取元素
print(student[0])   # 周杰轮
print(student[1])   # 11
print(student[2])   # ['football', 'music']
​
# 5. 修改元组内list的内容(可以)
student[2].remove('football')
print(student)   # ('周杰轮', 11, ['music'])
​
student[2].append('coding')
print(student)   # ('周杰轮', 11, ['music', 'coding'])
​
# 以下操作会报错(元组元素不可变)
# student[0] = "周杰伦"   # 报错!

3. 元组的遍历

复制代码
# for循环遍历
t = (1, 2, 3, 4, 5)
for num in t:
    print(num)
# 输出:1 2 3 4 5

# while循环遍历
i = 0
while i < len(t):
    print(t[i])
    i += 1
# 输出:1 2 3 4 5

四、字符串(str):重复有序

1. 字符串下标索引

复制代码
s = "itheima"

# 正向索引
print(s[0])   # i
print(s[3])   # e

# 反向索引
print(s[-1])   # a
print(s[-3])   # i

# 字符串不可修改
# s[0] = "I"   # 报错!

2. 字符串常用操作

复制代码
s = "  itheima itcast boxuegu  "

# 1. 查找子串下标
index = s.index("itcast")
print(index)   # 10(注意空格的影响)

# 2. 替换
new_s = s.replace(" ", "|")
print(new_s)   # "||itheima|itcast|boxuegu||"
print(s)       # 原字符串不变

# 3. 分割
words = "itheima itcast boxuegu".split(" ")
print(words)   # ['itheima', 'itcast', 'boxuegu']

# 4. 去除前后空格
s2 = "  hello world  "
print(s2.strip())        # hello world
print(s2.strip(" hd"))   # ello worl(去除指定字符)

# 5. 统计子串出现次数
s3 = "itheima itcast itheima"
count = s3.count("it")
print(count)   # 3

# 6. 统计字符串长度
print(len("itheima"))   # 7

3. 练习:分割字符串

复制代码
s = "itheima itcast boxuegu"

# 统计"it"出现次数
count = s.count("it")
print(count)   # 3

# 替换空格为"|"
new_s = s.replace(" ", "|")
print(new_s)   # itheima|itcast|boxuegu

# 按"|"分割得到列表
result = new_s.split("|")
print(result)   # ['itheima', 'itcast', 'boxuegu']

五、序列的切片

序列:内容连续、有序、可用下标索引的数据容器(列表、元组、字符串)

切片语法序列[起始:结束:步长]

复制代码
# 列表切片
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4])     # [2, 3, 4](下标1到3)
print(my_list[:3])      # [1, 2, 3](从头到下标2)
print(my_list[2:])      # [3, 4, 5](下标2到尾)
print(my_list[::2])     # [1, 3, 5](步长2)
print(my_list[::-1])    # [5, 4, 3, 2, 1](倒序)

# 元组切片
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4])    # (2, 3, 4)
print(my_tuple[::-1])   # (5, 4, 3, 2, 1)

# 字符串切片
my_str = "12345"
print(my_str[1:4])      # "234"
print(my_str[::-1])     # "54321"

# 复杂切片
print(my_list[3:1:-1])  # [4, 3](反向,从下标3到2)
print(my_tuple[:1:-2])  # (5, 3)(从头到尾,步长-2)

练习:字符串切片

复制代码
# 从"万过薪月,员序程马黑来,nohtyP学" 得到 "黑马程序员"

s = "万过薪月,员序程马黑来,nohtyP学"

# 方法1:替换+切片+反转
result = s.replace(",", "").replace("万过薪月", "").replace("员序程马", "").replace("nohtyP学", "")[::-1]
print(result)   # 黑马程序员

# 方法2:切片+反转
part = s[5:9]   # "黑来,n" → 需要调整

# 更简单的方法
result = s[7:9] + s[4:5] + s[15:18][::-1]
print(result)   # 黑马程序员

六、集合(set):去重无序

1. 集合的定义和特点

复制代码
# 定义集合
s1 = {1, 2, 3, 4, 5}
print(s1)   # {1, 2, 3, 4, 5}

# 自动去重
s2 = {1, 2, 2, 3, 3, 4}
print(s2)   # {1, 2, 3, 4}(重复元素自动去除)

# 混合类型
s3 = {1, "hello", 3.14}
print(s3)   # {1, 3.14, 'hello'}

# 定义空集合(不能用{},那是字典)
s4 = set()
print(s4)           # set()
print(type(s4))     # <class 'set'>

2. 集合常用操作

复制代码
my_set = {1, 2, 3, 4, 5}
print(my_set)   # {1, 2, 3, 4, 5}

# 1. 添加元素
my_set.add(6)
print(my_set)   # {1, 2, 3, 4, 5, 6}

# 2. 移除元素
my_set.remove(3)
print(my_set)   # {1, 2, 4, 5, 6}

# 3. 随机取出并移除元素
popped = my_set.pop()
print(popped)   # 随机元素
print(my_set)   # 剩余元素

# 4. 清空集合
my_set.clear()
print(my_set)   # set()

# 5. 取差集
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
diff = set1.difference(set2)
print(diff)      # {1, 2, 3}(set1有但set2没有的)
print(set1)      # {1, 2, 3, 4, 5}(不变)

# 6. 消除差集(修改集合)
set1.difference_update(set2)
print(set1)      # {1, 2, 3}(set1被修改)

# 7. 合并集合
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1.union(set2)
print(union)     # {1, 2, 3, 4, 5}
print(set1)      # {1, 2, 3}(不变)

# 8. 统计长度
print(len(union))   # 5

3. 集合的遍历

复制代码
my_set = {1, 2, 3, 4, 5}

# for循环遍历(集合不支持while)
for num in my_set:
    print(num)
# 输出:1 2 3 4 5(顺序不确定)

4. 练习:列表去重

复制代码
my_list = ['黑马程序员', '传智播客', '黑马程序员', '传智播客', 'itheima', 'itcast', 'itheima', 'itcast', 'best']

# 遍历列表添加到集合实现去重
my_set = set()
for item in my_list:
    my_set.add(item)

print(my_set)   # {'itcast', '传智播客', 'itheima', 'best', '黑马程序员'}
print(list(my_set))   # 转换为列表

七、字典(dict)

1. 字典的定义

复制代码
# 定义字典
student = {"name": "张三", "age": 18, "city": "北京"}
print(student)   # {'name': '张三', 'age': 18, 'city': '北京'}

# 获取值
print(student["name"])   # 张三
print(student["age"])    # 18

# 定义空字典
dict1 = {}
dict2 = dict()
print(dict1)   # {}
print(dict2)   # {}

2. 字典的嵌套

复制代码
# 嵌套字典
students = {
    "张三": {
        "age": 18,
        "score": 90
    },
    "李四": {
        "age": 19,
        "score": 85
    }
}

print(students["张三"]["score"])   # 90
print(students["李四"]["age"])     # 19

3. 字典常用操作

复制代码
# 定义字典
student = {"name": "张三", "age": 18}
print(student)   # {'name': '张三', 'age': 18}

# 1. 新增/更新元素
student["city"] = "北京"     # 新增
print(student)   # {'name': '张三', 'age': 18, 'city': '北京'}

student["age"] = 19          # 更新
print(student)   # {'name': '张三', 'age': 19, 'city': '北京'}

# 2. 删除元素
removed = student.pop("city")
print(removed)   # 北京
print(student)   # {'name': '张三', 'age': 19}

# 3. 获取所有keys
keys = student.keys()
print(keys)      # dict_keys(['name', 'age'])

# 4. 遍历字典
for key in student.keys():
    print(f"{key}: {student[key]}")
# 输出:
# name: 张三
# age: 19

# 更简洁的遍历
for key, value in student.items():
    print(f"{key}: {value}")
# 输出:
# name: 张三
# age: 19

# 5. 清空字典
student.clear()
print(student)   # {}

# 6. 统计键值对数量
print(len({"a": 1, "b": 2, "c": 3}))   # 3

4. 练习:升职加薪

复制代码
employees = {
    "张三": {"level": 1, "salary": 3000},
    "李四": {"level": 2, "salary": 4000},
    "王五": {"level": 1, "salary": 3500},
    "赵六": {"level": 3, "salary": 5000}
}

print("原始数据:")
for name, info in employees.items():
    print(f"{name}: 级别{info['level']}, 薪水{info['salary']}")

# 级别为1的员工升级加薪
for name, info in employees.items():
    if info["level"] == 1:
        info["level"] += 1
        info["salary"] += 1000

print("\n处理后:")
for name, info in employees.items():
    print(f"{name}: 级别{info['level']}, 薪水{info['salary']}")

# 输出:
# 原始数据:
# 张三: 级别1, 薪水3000
# 李四: 级别2, 薪水4000
# 王五: 级别1, 薪水3500
# 赵六: 级别3, 薪水5000
#
# 处理后:
# 张三: 级别2, 薪水4000
# 李四: 级别2, 薪水4000
# 王五: 级别2, 薪水4500
# 赵六: 级别3, 薪水5000

八、数据容器对比

1. 分类对比

特性 列表list 元组tuple 字符串str 集合set 字典dict
格式 [] () "" {} {key:val}
下标索引
元素重复 key不可重复
可修改
有序 ❌(Python3.7+有序)
支持while
支持for

2. 应用场景

复制代码
# 列表:可修改、可重复的顺序存储
scores = [85, 90, 78, 92, 85]

# 元组:不可修改、可重复的顺序存储
colors = ("red", "green", "blue")

# 字符串:字符序列
message = "Hello World"

# 集合:去重、无序
unique_numbers = {1, 2, 3, 2, 1}   # {1, 2, 3}

# 字典:键值对映射
person = {"name": "张三", "age": 18}

九、数据容器通用操作

1. 通用函数

复制代码
# len():统计元素个数
print(len([1, 2, 3]))       # 3
print(len((1, 2)))          # 2
print(len("hello"))         # 5
print(len({1, 2, 3}))       # 3
print(len({"a": 1, "b": 2})) # 2

# max():最大值
print(max([1, 5, 3]))       # 5
print(max("hello"))         # o(ASCII码最大)
print(max({"a": 1, "b": 2})) # b(键的最大值)

# min():最小值
print(min([1, 5, 3]))       # 1
print(min("hello"))         # e

2. 类型转换

复制代码
# 转换为列表
print(list((1, 2, 3)))      # [1, 2, 3]
print(list("hello"))        # ['h', 'e', 'l', 'l', 'o']
print(list({1, 2, 3}))      # [1, 2, 3]
print(list({"a": 1, "b": 2}))  # ['a', 'b']

# 转换为元组
print(tuple([1, 2, 3]))     # (1, 2, 3)
print(tuple("hello"))       # ('h', 'e', 'l', 'l', 'o')

# 转换为字符串
print(str([1, 2, 3]))       # "[1, 2, 3]"
print(str((1, 2, 3)))       # "(1, 2, 3)"

# 转换为集合
print(set([1, 2, 2, 3]))    # {1, 2, 3}(自动去重)
print(set("hello"))         # {'h', 'e', 'l', 'o'}

3. 排序

复制代码
# sorted():排序,返回列表
my_list = [3, 1, 4, 2, 5]
print(sorted(my_list))           # [1, 2, 3, 4, 5]
print(sorted(my_list, reverse=True))  # [5, 4, 3, 2, 1]

# 对元组排序
my_tuple = (3, 1, 4, 2, 5)
print(sorted(my_tuple))          # [1, 2, 3, 4, 5]

# 对字符串排序
print(sorted("hello"))           # ['e', 'h', 'l', 'l', 'o']

# 对集合排序
my_set = {3, 1, 4, 2, 5}
print(sorted(my_set))            # [1, 2, 3, 4, 5]

十、数据容器速查表

操作 列表 元组 字符串 集合 字典
定义 [1,2] (1,2) "ab" {1,2} {1:1,2:2}
索引 lst[0] tup[0] s[0] dict[key]
修改
添加 append() add() dict[key]=v
删除 pop()/remove() remove() pop()
查找 index() index() index() dict[key]
遍历 for x in lst for x in tup for x in s for x in s for k in d
长度 len() len() len() len() len()
相关推荐
知识领航员1 小时前
2026年推荐6个AI音乐工具
java·人工智能·python·eclipse·django·php·pygame
PieroPc1 小时前
证件裁切拼版工具
python
2401_833033622 小时前
golang如何实现MQTT主题通配符路由_golang MQTT主题通配符路由实现策略
jvm·数据库·python
AI精钢2 小时前
修复 AI Gateway 图片 MIME 类型错误:用魔数检测替代扩展名猜测
网络·人工智能·python·gateway·aigc
m0_596749092 小时前
Golang怎么实现方法集与接口的匹配_Golang如何理解值类型和指针类型实现接口的区别【详解】
jvm·数据库·python
隔壁小红馆3 小时前
隐藏odoo特有
python·odoo17·odoo18
lifewange3 小时前
pytest 找不到文件?直接在 pytest.ini 配置根目录 + 路径(最简单方案)
开发语言·python·pytest
yuanpan3 小时前
Python 桌面 GUI 入门开发:从 tkinter 窗口到简易记事本
开发语言·python
川石课堂软件测试3 小时前
软件测试|常见面试题整理
数据库·python·jmeter·mysql·appium·postman·prometheus