Python中的列表(List)和字典(Dictionary)是两种最常用的数据结构。列表类似于数组,字典是一种键值对数据结构。本文将详细介绍这两种数据结构的用法。

一、列表(List)

1. 基本操作

1
2
3
4
5
6
7
8
9
10
11
12
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# 访问元素
print(fruits[0]) # apple
print(fruits[-1]) # cherry

# 修改元素
fruits[0] = "orange"
print(fruits) # ['orange', 'banana', 'cherry']

2. 列表方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 添加元素
fruits = ["apple", "banana"]
fruits.append("cherry") # 末尾添加
fruits.insert(0, "orange") # 指定位置插入
fruits.extend(["grape", "melon"]) # 扩展列表

# 删除元素
fruits.remove("banana") # 移除第一个匹配项
fruits.pop() # 移除末尾元素
del fruits[0] # 删除指定位置元素

# 其他操作
fruits.sort() # 排序
fruits.reverse() # 反转
print(len(fruits)) # 长度
print("apple" in fruits) # 成员检查

3. 列表切片

1
2
3
4
5
6
7
numbers = [0, 1, 2, 3, 4, 5]

print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2]
print(numbers[3:]) # [3, 4, 5]
print(numbers[::2]) # [0, 2, 4]
print(numbers[::-1]) # [5, 4, 3, 2, 1, 0]

二、字典(Dictionary)

1. 基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 创建字典
person = {
"name": "Alice",
"age": 25,
"city": "Beijing"
}

# 访问元素
print(person["name"]) # Alice
print(person.get("age")) # 25
print(person.get("country", "Unknown")) # Unknown(默认值)

# 修改元素
person["age"] = 26
person["country"] = "China"

2. 字典方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
person = {"name": "Alice", "age": 25, "city": "Beijing"}

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

# 获取所有值
print(person.values()) # dict_values(['Alice', 25, 'Beijing'])

# 获取所有键值对
print(person.items()) # dict_items([('name', 'Alice'), ...])

# 删除元素
del person["city"]
age = person.pop("age")

# 更新字典
person.update({"country": "China", "age": 26})

3. 字典遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
person = {"name": "Alice", "age": 25, "city": "Beijing"}

# 遍历键
for key in person:
print(key)

# 遍历值
for value in person.values():
print(value)

# 遍历键值对
for key, value in person.items():
print(f"{key}: {value}")

三、综合示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
列表和字典综合示例
"""

def list_operations():
"""列表操作"""
print("=== 列表操作 ===")
numbers = [5, 2, 8, 1, 9]

# 添加
numbers.append(3)
print(f"添加后: {numbers}")

# 排序
numbers.sort()
print(f"排序后: {numbers}")

# 最大最小
print(f"最大值: {max(numbers)}")
print(f"最小值: {min(numbers)}")

# 求和
print(f"总和: {sum(numbers)}")

def dict_operations():
"""字典操作"""
print("\n=== 字典操作 ===")
students = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}

# 添加
students["David"] = 88
print(f"添加后: {students}")

# 更新
students["Alice"] = 90
print(f"更新后: {students}")

# 遍历
for name, score in students.items():
print(f"{name}: {score}")

def word_frequency():
"""统计单词频率"""
print("\n=== 单词频率统计 ===")
text = "apple banana apple cherry banana apple"
words = text.split()

frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1

print(f"频率统计: {frequency}")

def demo():
"""演示"""
list_operations()
dict_operations()
word_frequency()

if __name__ == "__main__":
demo()

四、注意事项

1. 列表是可变的

1
2
3
4
5
6
7
8
9
10
11
12
13
# 列表引用
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4](a也被修改)

# 复制列表
a = [1, 2, 3]
b = a.copy()
# 或 b = list(a)
# 或 b = a[:]
b.append(4)
print(a) # [1, 2, 3](a未被修改)

2. 字典键必须是可哈希的

1
2
3
4
5
# 可作为键的类型:字符串、数字、元组
valid_dict = {"a": 1, 1: 2, (1, 2): 3}

# 不可作为键的类型:列表、字典
# invalid_dict = {[1, 2]: 3} # 错误

3. 使用 defaultdict

1
2
3
4
5
6
7
from collections import defaultdict

# 自动创建默认值
d = defaultdict(int)
for char in "hello":
d[char] += 1
print(dict(d)) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}