Python3 列表(list) 元组(tuple)字典(dict)集合(set)使用  
   
所属分类 python
浏览量 133
列表(list) 元组(tuple)字典(dict)集合(set)
数据结构        有序性   可变性    唯一性 访问方式    典型应用
列表(List)    ✅      ✅        ❌     索引       动态数据存储、有序操作
元组(Tuple)   ✅      ❌        ❌     索引       不可变数据、函数返回多值
字典(Dict)    ❌      ✅        ✅    (键)键	  快速查找、键值映射
集合(Set)     ❌      ✅        ✅     无         去重、集合运算、成员检测
1. 列表(List)
列表是可变的、有序的数据结构,支持任意类型元素
# 创建列表
fruits = ['apple', 'banana', 'cherry']  # 直接初始化
numbers = list(range(5))  # 使用 list() 构造函数
mixed = [1, 'hello', True, [2, 4]]  # 混合类型元素
# 基本操作
fruits.append('date')  # 添加元素到末尾
fruits.insert(1, 'berry')  # 在指定位置插入元素
fruits.remove('cherry')  # 删除指定元素
popped = fruits.pop()  # 删除并返回最后一个元素
print(f"列表长度: {len(fruits)}")  # 输出: 3
# 索引与切片
print(fruits[0])  # 输出: apple
print(fruits[-1])  # 输出: banana (负索引表示从后往前)
print(fruits[1:3])  # 输出: ['berry', 'banana'] (切片: [start, end))
# 常用方法
fruits.sort()  # 原地排序
print(fruits)  # 输出: ['apple', 'banana', 'berry']
reversed_fruits = fruits[::-1]  # 反转列表
print(f"是否存在 'apple': {'apple' in fruits}")  # 成员检测
# 列表推导式
squares = [x**2 for x in numbers]  # 生成平方数列表
print(squares)  # 输出: [0, 1, 4, 9, 16]
my_list = [2, 3, 4]
my_list.insert(0, 1)  # 在第一个位置插入 1
print(my_list)  # 输出: [1, 2, 3, 4]
[1, 2, 3, 4]
print(my_list.pop())
4
my_list
[1, 2, 3]
2. 元组(Tuple)
元组是不可变的、有序的数据结构,常用于存储不可变的数据集合
# 创建元组
point = (3, 4)  # 直接初始化
colors = 'red', 'green', 'blue'  # 省略括号
single_element = (1,)  # 单元素元组需加逗号
# 基本操作
x, y = point  # 解包
print(f"x={x}, y={y}")  # 输出: x=3, y=4
# 索引与切片(与列表类似)
print(colors[0])  # 输出: red
print(colors[1:])  # 输出: ('green', 'blue')
# 不可变性(修改会报错)
try:
    colors[0] = 'yellow'  # TypeError: 'tuple' object does not support item assignment
except TypeError as e:
    print(f"错误: {e}")
# 常用方法
print(f"元素 'red' 的索引: {colors.index('red')}")  # 输出: 0
print(f"元素 'green' 出现次数: {colors.count('green')}")  # 输出: 1
# 应用场景:函数返回多值
def get_name_and_age():
    return 'Alice', 25
name, age = get_name_and_age()
print(f"{name} is {age} years old.")  # 输出: Alice is 25 years old.
3. 字典(Dict)
字典是可变的、无序的键值对集合,通过键快速查找值
# 创建字典
person = {
    'name': 'Bob',
    'age': 30,
    'city': 'New York'
}  # 直接初始化
empty_dict = dict()  # 使用 dict() 构造函数
# 基本操作
person['job'] = 'Engineer'  # 添加新键值对
person['age'] = 31  # 修改现有值
del person['city']  # 删除键值对
print(f"字典长度: {len(person)}")  # 输出: 3
# 访问值
print(person['name'])  # 输出: Bob
print(person.get('age', 0))  # 安全获取值,默认值为 0
# 常用方法
keys = person.keys()  # 获取所有键
values = person.values()  # 获取所有值
items = person.items()  # 获取所有键值对
print(f"是否存在键 'job': {'job' in person}")  # 键存在检测
# 字典推导式
squares_dict = {x: x**2 for x in range(5)}  # 生成平方数字典
print(squares_dict)  # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 遍历字典
for key, value in person.items():
    print(f"{key}: {value}")
4. 集合(Set)
集合是可变的、无序的、唯一的元素集合,常用于去重和成员检测
# 创建集合
fruits_set = {'apple', 'banana', 'cherry'}  # 直接初始化
empty_set = set()  # 注意:{} 是字典,不是集合!
numbers_set = set([1, 2, 2, 3, 3, 3])  # 从列表创建(自动去重)
print(f"去重后的集合: {numbers_set}")  # 输出: {1, 2, 3}
# 基本操作
fruits_set.add('date')  # 添加元素
fruits_set.remove('cherry')  # 删除元素
print(f"集合长度: {len(fruits_set)}")  # 输出: 3
# 集合运算
A = {1, 2, 3}
B = {3, 4, 5}
union = A | B  # 并集: {1, 2, 3, 4, 5}
intersection = A & B  # 交集: {3}
difference = A - B  # 差集: {1, 2}
symmetric_diff = A ^ B  # 对称差集: {1, 2, 4, 5}
# 成员检测与子集判断
print(f"是否存在 'apple': {'apple' in fruits_set}")  # 输出: True
print(f"A 是否是 B 的子集: {A.issubset(B)}")  # 输出: False
# 集合推导式
squares_set = {x**2 for x in range(5)}  # 生成平方数集合
print(squares_set)  # 输出: {0, 1, 4, 9, 16}
5. 综合应用示例
结合四种数据结构解决实际问题:统计文本中单词出现频率
text = "hello world hello python world code"
words = text.split()  # 分割为单词列表
# 使用字典统计词频
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
# 输出统计结果(按频率排序)
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_words:
    print(f"{word}: {count}")
# 提取唯一单词(使用集合去重)
unique_words = set(words)
print(f"唯一单词: {unique_words}")
sorted() 函数对字典的 items() 进行排序,返回一个由元组组成的列表
student_scores = {"Alice": 85, "Bob": 72, "Charlie": 90, "David": 72}
# 按值降序排序,返回元组列表
sorted_by_value = sorted(student_scores.items(), key=lambda item: item[1],reverse=True )
print(sorted_by_value)
# [('Charlie', 90), ('Alice', 85), ('Bob', 72), ('David', 72)]
 上一篇  
   
 下一篇  
 Mac笔记本大模型本地化部署 
 向量数据库 基本概念 技术原理 选型指南 
 python3  实用代码 
 向量数据库在 RAG 检索增强生成中的应用 
 向量数据库相关的核心概念和术语 
 向量数据库选型