3. 数据结构
3.1 列表 (list)
列表是一种有序的、可变的数据结构,能够存储任意类型的元素。
3.1.1 列表的创建与操作
创建列表:
# 创建一个包含整数的列表
numbers = [1, 2, 3, 4, 5]
# 创建一个空列表
empty_list = []
# 创建一个包含不同数据类型的列表
mixed_list = [1, "hello", 3.14, True]
# 输出结果
# numbers = [1, 2, 3, 4, 5]
# empty_list = []
# mixed_list = [1, "hello", 3.14, True]
基本操作:
# 访问元素
first_element = numbers[0] # 1
last_element = numbers[-1] # 5
# 添加元素
numbers.append(6) # [1, 2, 3, 4, 5, 6]
# 删除元素
numbers.remove(3) # [1, 2, 4, 5, 6]
# 修改元素
numbers[1] = 10 # [1, 10, 4, 5, 6]
# 列表长度
length = len(numbers) # 5
3.1.2 列表推导式
列表推导式是一种简洁的方式来创建列表。
示例:
# 使用列表推导式生成平方数列表
squares = [x ** 2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
# 使用条件的列表推导式
even_squares = [x ** 2 for x in range(1, 6) if x % 2 == 0] # [4, 16]
3.2 元组 (tuple)
元组与列表类似,但它是不可变的,意味着一旦创建便无法修改。
3.2.1 元组的创建与操作
创建元组:
# 创建一个包含整数的元组
numbers = (1, 2, 3, 4, 5)
# 创建一个单元素元组,注意逗号
single_element_tuple = (1,)
# 输出结果
# numbers = (1, 2, 3, 4, 5)
# single_element_tuple = (1,)
基本操作:
# 访问元素
first_element = numbers[0] # 1
last_element = numbers[-1] # 5
# 获取元组长度
length = len(numbers) # 5
# 元组解包
a, b, c, d, e = numbers # a=1, b=2, c=3, d=4, e=5
# 由于元组是不可变的,无法进行添加、删除或修改操作。
3.3 集合 (set)
集合是一种无序的、元素唯一的数据结构,常用于去重操作。
3.3.1 集合的创建与操作
创建集合:
# 创建一个包含整数的集合
numbers = {1, 2, 3, 4, 5}
# 创建一个空集合
empty_set = set()
# 输出结果
# numbers = {1, 2, 3, 4, 5}
# empty_set = set()
基本操作:
# 添加元素
numbers.add(6) # {1, 2, 3, 4, 5, 6}
# 删除元素
numbers.remove(3) # {1, 2, 4, 5, 6}
# 集合之间的操作
another_set = {4, 5, 6, 7}
union_set = numbers.union(another_set) # {1, 2, 4, 5, 6, 7}
intersection_set = numbers.intersection(another_set) # {4, 5, 6}
difference_set = numbers.difference(another_set) # {1, 2}
3.4 字典 (dict)
字典是一种键值对的数据结构,键必须是唯一的。
3.4.1 字典的创建与操作
创建字典:
# 创建一个字典
person = {"name": "Alice", "age": 30, "city": "New York"}
# 创建一个空字典
empty_dict = {}
# 输出结果
# person = {"name": "Alice", "age": 30, "city": "New York"}
# empty_dict = {}
基本操作:
# 访问值
name = person["name"] # "Alice"
# 添加或修改键值对
person["age"] = 31 # {"name": "Alice", "age": 31, "city": "New York"}
person["country"] = "USA" # {"name": "Alice", "age": 31, "city": "New York", "country": "USA"}
# 删除键值对
del person["city"] # {"name": "Alice", "age": 31, "country": "USA"}
# 获取所有键或值
keys = person.keys() # dict_keys(['name', 'age', 'country'])
values = person.values() # dict_values(['Alice', 31, 'USA'])
3.4.2 字典推导式
字典推导式用于生成新的字典。
示例:
# 使用字典推导式创建一个字典,键是1到5,值是它们的平方
squares_dict = {x: x ** 2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 条件字典推导式
even_squares_dict = {x: x ** 2 for x in range(1, 6) if x % 2 == 0} # {2: 4, 4: 16}