Python 数据结构
掌握列表、元组、字典、集合,并理解它们各自适合的使用场景。
1. 列表 list
列表用于存储一组有序、可变的数据。
fruits = ["apple", "banana", "orange"]
print(fruits[0])
fruits.append("pear")
for fruit in fruits:
print(fruit)
2. 列表切片
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])
print(nums[:3])
print(nums[::-1])
3. 列表推导式
squares = [x * x for x in range(1, 6)]
evens = [x for x in range(10) if x % 2 == 0]
4. 元组 tuple
元组是有序、不可变的数据结构,适合保存不希望被修改的数据。
point = (10, 20)
x, y = point
single = (1,)
5. 字典 dict
字典使用键值对存储数据。
student = {
"name": "小明",
"age": 18,
"score": 95,
}
print(student.get("name"))
student["city"] = "杭州"
6. 集合 set
集合用于去重和集合运算。
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(a & b)
print(a - b)
本章总结
列表适合保存可变序列,元组适合固定数据,字典适合映射关系,集合适合去重和集合运算。