ToolkitX
知识库工具箱

数据结构

列表、元组、字典、集合

20min·入门

01. 列表 (List)

列表是 Python 中最常用的数据结构,是一个有序、可变的集合。列表可以存储任意类型的元素。 常用操作:append() 末尾添加,insert() 指定位置插入,pop() 删除并返回,sort() 原地排序,切片 [start:end:step] 获取子列表。
python
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]

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

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

# 列表方法
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.remove("banana")
popped = fruits.pop()

# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

# 排序
nums = [3, 1, 4, 1, 5, 9]
nums.sort()
print(nums)  # [1, 1, 3, 4, 5, 9]

02. 元组 (Tuple)

元组是有序、不可变的序列。一旦创建就不能修改。常用于存储不应被修改的数据,如坐标、数据库记录等。 元组解包是 Python 的强大特性,可以一次性将元组中的值赋给多个变量。
python
# 创建元组
point = (10, 20)
colors = ("red", "green", "blue")
single = (42,)  # 单元素元组必须加逗号

# 元组解包
x, y = point
a, b, c = colors

# 交换变量
a, b = b, a

# 函数多返回值
def get_min_max(numbers):
return min(numbers), max(numbers)

lo, hi = get_min_max([3, 1, 4, 1, 5, 9])
元组比列表更节省内存,且可以作为字典的键。

03. 字典 (Dict)

字典是键值对的无序集合(Python 3.7+ 保持插入顺序)。键必须是不可变类型(字符串、数字、元组),值可以是任意类型。
python
# 创建字典
user = {"name": "Alice", "age": 25, "city": "Beijing"}

# 访问
print(user["name"])          # Alice
print(user.get("email", "N/A"))

# 修改和添加
user["age"] = 26
user["email"] = "[email protected]"

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

# 字典推导式
squares = {x: x**2 for x in range(6)}

# 统计词频
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = {}
for word in words:
  count[word] = count.get(word, 0) + 1

04. 集合 (Set)

集合是无序、不重复的元素集合。支持数学集合运算:并集、交集、差集、对称差集。常用于去重和成员检测。
python
# 创建集合
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 3, 4, 4])  # {1, 2, 3, 4}

# 集合运算
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}
print(a ^ b)   # 对称差集: {1, 2, 5, 6}

# 去重
data = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(data))

知识测验

1/5正确 0

列表和元组的主要区别是什么?

下一节

函数与模块

下一节