前言
Python 提供了多种内置数据类型来存储和操作数据,其中 列表、元组、字典 和 集合 是最常用的四种数据结构。它们在特性、用途和操作上各有不同,适用于不同的场景
1. 列表
1.1 什么是列表
列表(
list
)是一个有序的、可变的集合,可以包含任意类型的元素使用方括号
[]
定义,元素之间用逗号,
分隔
1.2 列表操作
1.2.1 创建列表
# 创建空列表
empty_list = []
# 含有多个元素的列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True]
1.2.2 访问和修改列表元素
通过索引访问或修改元素,索引从 0
开始
fruits = ["apple", "banana", "cherry"]
# 访问元素
print(fruits[0]) # 输出 "apple"
print(fruits[-1]) # 输出 "cherry"
# 修改元素
fruits[1] = "blueberry"
print(fruits) # 输出 ['apple', 'blueberry', 'cherry']
1.2.3 列表常用方法
1.3 列表推导式
列表推导式是生成列表的简洁方式。
# 创建一个包含1到10的平方的列表
# 正常版本
squares = []
for x in range(1, 11):
squares.append(x**2)
print(squares) # 输出 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 推导式版本
squares = [x**2 for x in range(1, 11)]
print(squares) # 输出 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2. 元组
2.1 什么是元组
元组(
tuple
)是一个有序的、不可变的集合使用小括号
()
定义,元素之间用逗号,
分隔
2.2 元组操作
2.2.1 创建元组
# 空元组
empty_tuple = ()
# 单元素元组(注意逗号)
single_element_tuple = (42,)
# 多元素元组
coordinates = (10, 20, 30)
fruits = ("apple", "banana", "cherry")
2.2.2 访问元组元素
元组的访问方式与列表类似,使用索引
fruits = ("apple", "banana", "cherry")
# 访问元素
print(fruits[0]) # 输出 "apple"
print(fruits[-1]) # 输出 "cherry"
2.2.3 元组不可变性
元组中的元素一旦定义,就无法修改
fruits = ("apple", "banana", "cherry")
# fruits[0] = "pear" # 会报错:TypeError: 'tuple' object does not support item assignment
2.3 元组的特殊方法
3. 字典
3.1 什么是字典
字典(
dict
)是一个无序的、可变的键值对集合使用大括号
{}
定义,键和值之间用冒号:
分隔
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
3.2 字典操作
3.2.1 访问和修改字典
person = {"name": "Alice", "age": 25}
# 访问值
print(person["name"]) # 输出 "Alice"
print(person.get("age")) # 输出 25
# 修改值
person["age"] = 30
print(person) # 输出 {'name': 'Alice', 'age': 30}
3.2.2 添加和删除键值对
# 添加键值对
person["gender"] = "Female"
# 删除键值对
del person["age"]
3.2.3 字典常用方法
3.3 遍历字典
person = {"name": "Alice", "age": 30}
for key, value in person.items():
print(f"{key}: {value}")
运行结果:
name: Alice
age: 30
4. 集合
4.1 什么是集合
集合(
set
)是一个无序的、不重复的元素集合使用大括号
{}
定义,或通过set()
函数创建
4.2 集合操作
4.2.1 创建集合
# 创建集合
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 2, 3, 4])
4.2.2 添加和删除元素
4.3 集合运算
集合支持常见的运算
4.4 遍历集合
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
运行结果:(顺序可能不同)
apple
banana
cherry