← 返回主页

第5课: 列表、元组与字典

列表 (List)

列表是Python中最常用的数据结构,可以存储多个元素,元素可以是不同类型。

创建列表

# 空列表
empty_list = []

# 包含元素的列表
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

print(fruits)  # ['苹果', '香蕉', '橙子']

访问列表元素

fruits = ["苹果", "香蕉", "橙子", "葡萄"]

# 索引从0开始
print(fruits[0])   # 苹果
print(fruits[2])   # 橙子

# 负索引从末尾开始
print(fruits[-1])  # 葡萄
print(fruits[-2])  # 橙子

# 切片
print(fruits[1:3])   # ['香蕉', '橙子']
print(fruits[:2])    # ['苹果', '香蕉']
print(fruits[2:])    # ['橙子', '葡萄']

修改列表

fruits = ["苹果", "香蕉", "橙子"]

# 修改元素
fruits[1] = "草莓"
print(fruits)  # ['苹果', '草莓', '橙子']

# 添加元素
fruits.append("葡萄")        # 末尾添加
fruits.insert(1, "西瓜")     # 指定位置插入
print(fruits)  # ['苹果', '西瓜', '草莓', '橙子', '葡萄']

# 删除元素
fruits.remove("草莓")        # 删除指定值
del fruits[0]                # 删除指定索引
last = fruits.pop()          # 删除并返回最后一个元素
print(fruits)

列表常用方法

numbers = [3, 1, 4, 1, 5, 9, 2]

# 排序
numbers.sort()               # 原地排序
print(numbers)               # [1, 1, 2, 3, 4, 5, 9]

sorted_nums = sorted([3, 1, 4])  # 返回新列表
print(sorted_nums)           # [1, 3, 4]

# 反转
numbers.reverse()
print(numbers)               # [9, 5, 4, 3, 2, 1, 1]

# 其他方法
print(numbers.count(1))      # 2 (统计1出现的次数)
print(numbers.index(5))      # 1 (查找5的索引)
print(len(numbers))          # 7 (列表长度)

元组 (Tuple)

元组与列表类似,但元组是不可变的,一旦创建就不能修改。

创建元组

# 使用圆括号
coordinates = (10, 20)
person = ("张三", 25, "北京")

# 单元素元组需要逗号
single = (42,)

# 不使用括号
point = 3, 4
print(type(point))  # 

访问元组元素

person = ("张三", 25, "北京")

print(person[0])     # 张三
print(person[-1])    # 北京
print(person[1:3])   # (25, '北京')

# 元组解包
name, age, city = person
print(name)  # 张三
print(age)   # 25

元组的优势

字典 (Dictionary)

字典是键值对的集合,使用键来访问值。

创建字典

# 空字典
empty_dict = {}

# 包含数据的字典
student = {
    "name": "张三",
    "age": 20,
    "grade": "大二",
    "scores": [85, 90, 88]
}

# 使用dict()函数
person = dict(name="李四", age=25)

访问和修改字典

student = {"name": "张三", "age": 20, "grade": "大二"}

# 访问值
print(student["name"])           # 张三
print(student.get("age"))        # 20
print(student.get("phone", "无")) # 无 (键不存在时返回默认值)

# 修改值
student["age"] = 21

# 添加新键值对
student["phone"] = "13800138000"

# 删除键值对
del student["grade"]
age = student.pop("age")         # 删除并返回值

print(student)

字典常用方法

student = {"name": "张三", "age": 20, "city": "北京"}

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

# 获取所有值
print(student.values())  # dict_values(['张三', 20, '北京'])

# 获取所有键值对
print(student.items())   # dict_items([('name', '张三'), ...])

# 遍历字典
for key, value in student.items():
    print(f"{key}: {value}")

# 检查键是否存在
if "name" in student:
    print("name键存在")

# 更新字典
student.update({"grade": "大二", "phone": "13800138000"})

字典推导式

# 创建平方字典
squares = {x: x**2 for x in range(5)}
print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 带条件的字典推导式
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)  # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

集合 (Set)

集合是无序的、不重复的元素集合。

# 创建集合
fruits = {"苹果", "香蕉", "橙子"}
numbers = set([1, 2, 2, 3, 3, 4])  # {1, 2, 3, 4}

# 添加和删除
fruits.add("葡萄")
fruits.remove("香蕉")

# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # 并集: {1, 2, 3, 4, 5, 6}
print(a & b)  # 交集: {3, 4}
print(a - b)  # 差集: {1, 2}

练习

  1. 创建一个学生列表,包含至少5个学生姓名,实现添加、删除、排序操作
  2. 创建一个字典存储商品信息(名称、价格、库存),实现查询和更新功能
  3. 使用字典统计一段文本中每个单词出现的次数
  4. 创建两个集合,求它们的并集、交集和差集
练习答案:
# 练习1:学生列表操作
students = ["张三", "李四", "王五", "赵六", "钱七"]
students.append("孙八")
students.remove("王五")
students.sort()
print(students)

# 练习2:商品字典
product = {
    "name": "笔记本电脑",
    "price": 5999,
    "stock": 50
}
print(f"商品: {product['name']}, 价格: {product['price']}")
product["stock"] -= 1  # 售出一件
print(f"剩余库存: {product['stock']}")

# 练习3:单词计数
text = "python is great python is easy"
words = text.split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)  # {'python': 2, 'is': 2, 'great': 1, 'easy': 1}

# 练习4:集合运算
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(f"并集: {set1 | set2}")
print(f"交集: {set1 & set2}")
print(f"差集: {set1 - set2}")