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]) print(fruits[-1])
fruits[0] = "orange" print(fruits)
|
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]) print(numbers[:3]) print(numbers[3:]) print(numbers[::2]) print(numbers[::-1])
|
二、字典(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"]) print(person.get("age")) print(person.get("country", "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())
print(person.values())
print(person.items())
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
|
""" 列表和字典综合示例 """
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)
a = [1, 2, 3] b = a.copy()
b.append(4) print(a)
|
2. 字典键必须是可哈希的
1 2 3 4 5
| valid_dict = {"a": 1, 1: 2, (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))
|