上一篇介绍了Python的环境搭建和基础语法。本篇将深入讲解Python中的核心数据结构——列表、元组、字典和集合,这些是组织和管理数据的核心工具,掌握它们是从“写出代码”到“写出有用代码”的关键一步。
一、列表:有序可变的序列
列表是Python中最常用的数据结构,用于存储有序的、可变的元素集合。列表用方括号[]表示,元素之间用逗号分隔。
python
fruits = ["apple", "banana", "cherry"] numbers = [1, 2, 3, 4, 5] mixed = [1, "hello", 3.14, True] # 列表可以混合不同类型 empty = [] # 空列表
访问元素:通过索引访问,索引从0开始。负索引从末尾开始计数(-1是最后一个元素)。
python
print(fruits[0]) # apple print(fruits[-1]) # cherry print(fruits[1:3]) # ['banana', 'cherry'] 切片操作
切片是列表操作的重要特性:list[start:end:step],包含start不包含end。
python
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(numbers[2:6]) # [2, 3, 4, 5] print(numbers[:5]) # [0, 1, 2, 3, 4] print(numbers[5:]) # [5, 6, 7, 8, 9] print(numbers[::2]) # [0, 2, 4, 6, 8] step为2
修改列表:列表是可变的,可以修改任意位置的元素。
python
fruits[1] = "blueberry" # 修改元素 fruits.append("orange") # 在末尾添加 fruits.insert(0, "grape") # 在指定位置插入 fruits.remove("apple") # 删除第一个匹配的元素 popped = fruits.pop() # 弹出并返回最后一个元素 del fruits[0] # 删除指定位置的元素列表推导式是Python独特的简洁语法,用于从现有列表创建新列表:
python
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] evens = [x for x in range(20) if x % 2 == 0] # 带条件筛选
二、元组:不可变的序列
元组与列表类似,但一旦创建就不能修改。元组用圆括号()表示。
python
coords = (10, 20) person = ("Alice", 25, "Engineer") single = (42,) # 单个元素的元组需要加逗号 empty = () # 空元组元组的主要用途:
作为字典的键(列表不可以)
保护数据不被意外修改
函数返回多个值时使用
python
x, y = coords # 元组解包 print(x, y) # 10 20 # 解包也可以用于列表 a, b, c = [1, 2, 3]
三、字典:键值对的映射
字典是Python中另一种重要的数据结构,用于存储键值对,通过键快速访问值。字典用花括号{}表示。
python
person = { "name": "Bob", "age": 30, "city": "New York" } print(person["name"]) # Bob print(person.get("age", 0)) # 30,get方法可以指定默认值字典操作:
python
person["job"] = "Engineer" # 添加新键值对 person["age"] = 31 # 修改已有键的值 del person["city"] # 删除键值对 # 遍历字典 for key in person: print(key, person[key]) for key, value in person.items(): print(f"{key}: {value}") # 检查键是否存在 if "name" in person: print("Name exists")四、集合:无序不重复的元素
集合用于存储不重复的元素,适合去重和集合运算(并集、交集、差集)。集合用花括号{}表示。
python
colors = {"red", "green", "blue"} mixed = {1, 2, "hello"} # 混合类型可以 empty = set() # 空集合不能使用{},因为{}被字典占用 # 添加和移除 colors.add("yellow") colors.remove("red") # 如果元素不存在会报错 colors.discard("purple") # 如果元素不存在不会报错 # 集合运算 set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} print(set1 | set2) # 并集 {1,2,3,4,5,6} print(set1 & set2) # 交集 {3,4} print(set1 - set2) # 差集 {1,2} print(set1 ^ set2) # 对称差集 {1,2,5,6}五、字符串的进阶操作
字符串是不可变的字符序列,提供了丰富的操作方法。
字符串方法:
python
text = " Hello, World! " print(text.strip()) # "Hello, World!" 去除首尾空白 print(text.lower()) # " hello, world! " print(text.upper()) # " HELLO, WORLD! " print(text.replace("World", "Python")) # 替换 print(text.split(",")) # [' Hello', ' World! '] # 判断方法 print(text.isdigit()) # 是否全是数字 print(text.isalpha()) # 是否全是字母 print(text.startswith("Hello")) # True print(text.endswith("!")) # True格式化字符串有多种方式:
python
name = "Alice" age = 25 # f-string(Python 3.6+,推荐) print(f"Name: {name}, Age: {age}") # format方法 print("Name: {}, Age: {}".format(name, age)) # 旧式%格式化 print("Name: %s, Age: %d" % (name, age))六、遍历数据结构的多种方式
python
# 遍历列表 fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # 带索引遍历 for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # 同时遍历多个列表 names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] for name, age in zip(names, ages): print(f"{name} is {age} years old")七、常见错误与最佳实践
IndexError: list index out of range:索引越界,检查列表长度KeyError:访问了字典中不存在的键,使用get()方法可以避免列表在循环中修改时可能导致意外行为,应使用切片或新列表
使用
in操作符检查元素是否存在,避免直接访问可能不存在的索引或键使用
copy()方法复制列表,防止引用传递的混淆
八、小结
本篇介绍了Python中四种核心数据结构:列表、元组、字典和集合,并扩展了字符串操作的常用方法。列表适合存储有序可变序列,元组适合存储不可变数据,字典适合通过键快速查找值,集合适合去重和集合运算。这些数据结构是编写Python程序的基础工具,建议在实际编码中反复练习。下一篇将介绍文件操作和异常处理机制。