Python学习-数据结构
- [1. 字符串(String)](#1. 字符串(String))
- [2. 列表(List)](#2. 列表(List))
- [3. 元组(Tuple)](#3. 元组(Tuple))
- [4. 集合(Set)](#4. 集合(Set))
- [5. 字典(Dictionary)](#5. 字典(Dictionary))
- [6. 可变与不可变数据结构](#6. 可变与不可变数据结构)
- [7. 数据结构的嵌套](#7. 数据结构的嵌套)
1. 字符串(String)
字符串是不可变的字符序列,字符串在 Python 中是 Unicode 字符的序列
python
# 创建字符串
my_str = "Hello, World!"
# 访问字符
print(my_str[0]) # 输出: H
# 字符串切片
print(my_str[7:12]) # 输出: World
# 字符串连接
new_str = my_str + " Welcome to Python!"
print(new_str) # 输出: Hello, World! Welcome to Python!
# 字符串方法
print(my_str.lower()) # 输出: hello, world!
print(my_str.upper()) # 输出: HELLO, WORLD!
print(my_str.replace("World", "Python")) # 输出: Hello, Python!
print(my_str.find("World")) # 输出 7
my_str = "apple, banana, cherry"
fruits = my_str.split(", ")
print(fruits) # 输出: ['apple', 'banana', 'cherry']
fruits = ['apple', 'banana', 'cherry']
my_str = ", ".join(fruits)
print(my_str) # 输出: apple, banana, cherry
my_str = " Hello, World! "
trimmed_str = my_str.strip()
print(trimmed_str) # 输出: Hello, World!
常用方法:
- lower(): 返回字符串的小写版本
- upper(): 返回字符串的大写版本
- replace(old, new): 将字符串中的 old 替换为 new
- split(sep): 根据 sep 分割字符串,返回一个列表
- join(iterable): 将可迭代对象中的字符串连接成一个字符串
- find(substring): 返回子字符串第一次出现的索引,若未找到则返回 -1
- strip(): 去除字符串两端的空白字符(包括空格、tab、换行符等)
2. 列表(List)
列表是 Python 中最常用的数据结构之一,它是有序的、可变的、允许重复元素的集合
python
# 创建列表
my_list = [1, 2, 3, 4, 5]
# 访问元素
print(my_list[0]) # 输出: 1
# 修改元素
my_list[1] = 10
print(my_list) # 输出: [1, 10, 3, 4, 5]
# 添加元素
my_list.append(6)
print(my_list) # 输出: [1, 10, 3, 4, 5, 6]
# 删除元素
my_list.remove(3)
print(my_list) # 输出: [1, 10, 4, 5, 6]
# 列表切片
print(my_list[1:4]) # 输出: [10, 4, 5]
# 添加迭代对象至尾部
my_list = [1, 2, 3]
other_list = [4, 5, 6]
my_list.extend(other_list)
print(my_list) # 输出: [1, 2, 3, 4, 5, 6]
#指定位置添加元素
my_list = [1, 2, 4, 5]
my_list.insert(2, 3)
print(my_list) # 输出: [1, 2, 3, 4, 5]
#删除指定位置元素
my_list = [1, 2, 3, 4, 5]
last_element = my_list.pop()
print(last_element) # 输出: 5
print(my_list) # 输出: [1, 2, 3, 4]
second_element = my_list.pop(1)
print(second_element) # 输出: 2
print(my_list) # 输出: [1, 3, 4]
# 清空列表
my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list) # 输出: []
# 返回匹配元素索引
my_list = [1, 2, 3, 4, 5, 3]
index_of_3 = my_list.index(3)
print(index_of_3) # 输出: 2
# 返还指定元素出现的次数
my_list = [1, 2, 3, 4, 5, 3, 3]
count_of_3 = my_list.count(3)
print(count_of_3) # 输出: 3
# 列表排序(默认升序)
my_list = [3, 1, 4, 1, 5, 9, 2, 6]
my_list.sort()
print(my_list) # 输出: [1, 1, 2, 3, 4, 5, 6, 9]
# 降序排序
my_list.sort(reverse=True)
print(my_list) # 输出: [9, 6, 5, 4, 3, 2, 1, 1]
# 列表反转
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # 输出: [5, 4, 3, 2, 1]
常用方法:
- append(x): 在列表末尾添加一个元素
- extend(iterable): 将可迭代对象的元素添加到列表末尾
- insert(i, x): 在指定位置插入元素
- remove(x): 删除第一个匹配的元素
- pop([i]): 删除并返回指定位置的元素,若未指定位置,则删除并返回最后一个元素
- clear(): 删除列表中的所有元素(Python3才支持)
- index(x): 返回第一个匹配元素的索引
- count(x): 返回元素 x 在列表中出现的次数
- sort(): 对列表进行排序
- reverse(): 反转列表中的元素顺序
3. 元组(Tuple)
元组是不可变的、有序的、可重复元素的集合,元组的不可变性意味着一旦创建,就不能修改其内容
python
# 创建元组
my_tuple = (1, 2, 3, 4, 5)
# 访问元素
print(my_tuple[0]) # 输出: 1
# 元组不可修改,尝试修改会报错
# my_tuple[1] = 10 # 这行代码会引发 TypeError
# 元组的切片
print(my_tuple[1:4]) # 输出: (2, 3, 4)
# 计算元组中指定元素出现的频次
my_tuple = (1, 2, 2, 3, 4, 2, 5)
count_of_2 = my_tuple.count(2)
print(count_of_2) # 输出: 3
# 获取指定元素的第一个索引
my_tuple = (1, 2, 2, 3, 4, 2, 5)
index_of_2 = my_tuple.index(2)
print(index_of_2) # 输出: 1
# 查找元素 10 的索引(会抛出 ValueError)
try:
index_of_10 = my_tuple.index(10)
print(index_of_10)
except ValueError as e:
print(e) # 输出: tuple.index(x): x not in tuple
# 在指定范围内查找元素
index_of_2_in_range = my_tuple.index(2, 2, 5)
print(index_of_2_in_range) # 输出: 2
常用方法:
- count(x): 返回元素 x 在元组中出现的次数
- index(x): 返回第一个匹配元素的索引
4. 集合(Set)
python
集合是无序的、不可重复的元素集合,集合不支持索引操作,因为它的元素是无序的
python
# 创建集合
my_set = {1, 2, 3, 4, 5}
# 添加元素
my_set.add(6)
print(my_set) # 输出: {1, 2, 3, 4, 5, 6}
# 删除元素
my_set.remove(3)
print(my_set) # 输出: {1, 2, 4, 5, 6}
# 集合操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
print(set1 | set2) # 输出: {1, 2, 3, 4, 5}
# 交集
print(set1 & set2) # 输出: {3}
# 差集
print(set1 - set2) # 输出: {1, 2}
# 删除元素,若不存在则不报错
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set) # 输出: {1, 2, 4, 5}
# 使用 discard 移除不存在的元素 10(不会报错)
my_set.discard(10)
print(my_set) # 输出: {1, 2, 4, 5}
# 使用pop删除元素
my_set = {1, 2, 3, 4, 5}
removed_element = my_set.pop()
print(removed_element) # 输出: 随机返回一个元素,例如 1
print(my_set) # 输出: 移除元素后的集合,例如 {2, 3, 4, 5}
# 尝试从空集合中 pop 元素会抛出 KeyError
empty_set = set()
try:
empty_set.pop()
except KeyError as e:
print(e) # 输出: 'pop from an empty set'
# 清空元素
my_set = {1, 2, 3, 4, 5}
my_set.clear()
print(my_set) # 输出: set()
常用方法:
- add(x): 添加元素 x 到集合
- remove(x): 删除元素 x,若 x 不存在则引发 KeyError
- discard(x): 删除元素 x,若 x 不存在则不报错
- pop(): 删除并返回集合中的任意一个元素,若集合为空则引发 KeyError
- clear(): 删除集合中的所有元素
- union(set): 返回两个集合的并集,等价于|
- intersection(set): 返回两个集合的交集,等价于&
- difference(set): 返回两个集合的差集,等价于-
5. 字典(Dictionary)
字典是一种键值对的映射结构,键必须是唯一的且不可变(通常是字符串或数字),值可以是任意类型
python
# 创建字典
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 访问元素
print(my_dict['name']) # 输出: Alice
# 修改元素
my_dict['age'] = 26
print(my_dict) # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York'}
# 添加元素
my_dict['gender'] = 'Female'
print(my_dict) # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'gender': 'Female'}
# 删除元素
del my_dict['city']
print(my_dict) # 输出: {'name': 'Alice', 'age': 26, 'gender': 'Female'}
# 使用 keys 获取所有键
keys = my_dict.keys()
print(keys) # 输出: dict_keys(['name', 'age', 'city'])
# 使用 values 获取所有值
values = my_dict.values()
print(values) # 输出: dict_values(['Alice', 25, 'New York'])
# 使用 items 获取所有键值对
items = my_dict.items()
print(items) # 输出: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
# 使用 get 获取键 'name' 的值
name = my_dict.get('name')
print(name) # 输出: Alice
# 使用 get 获取不存在的键 'gender',并指定默认值 'Unknown'
gender = my_dict.get('gender', 'Unknown')
print(gender) # 输出: Unknown
# 使用 pop 移除键 'age' 并返回其值
age = my_dict.pop('age')
print(age) # 输出: 25
print(my_dict) # 输出: {'name': 'Alice', 'city': 'New York'}
# 使用 pop 尝试移除不存在的键 'gender',并指定默认值 'Unknown'
gender = my_dict.pop('gender', 'Unknown')
print(gender) # 输出: Unknown
print(my_dict) # 输出: {'name': 'Alice', 'city': 'New York'}
# 定义一个字典
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 使用 popitem 移除并返回最后一个键值对
item = my_dict.popitem()
print(item) # 输出: ('city', 'New York')
print(my_dict) # 输出: {'name': 'Alice', 'age': 25}
# 尝试从空字典中 popitem 会抛出 KeyError
empty_dict = {}
try:
empty_dict.popitem()
except KeyError as e:
print(e) # 输出: 'popitem(): dictionary is empty'
# 使用 clear 清空字典
my_dict.clear()
print(my_dict) # 输出: {}
# 定义一个字典
my_dict = {'name': 'Alice', 'age': 25}
# 使用 update 合并另一个字典
other_dict = {'city': 'New York', 'gender': 'Female'}
my_dict.update(other_dict)
print(my_dict) # 输出: {'name': 'Alice', 'age': 25, 'city': 'New York', 'gender': 'Female'}
# 使用 update 添加单个键值对
my_dict.update({'occupation': 'Engineer'})
print(my_dict) # 输出: {'name': 'Alice', 'age': 25, 'city': 'New York', 'gender': 'Female', 'occupation': 'Engineer'}
常用方法:
- keys(): 返回字典中所有键的视图
- values(): 返回字典中所有值的视图
- items(): 返回字典中所有键值对的视图
- get(key): 返回指定键的值,若键不存在则返回 None 或指定的默认值
- pop(key): 删除并返回指定键的值,若键不存在则引发 KeyError
- popitem(): 删除并返回字典中的最后一个键值对,若字典为空则引发 KeyError
- clear(): 删除字典中的所有元素
- update(other_dict): 将另一个字典的键值对更新到当前字典中
6. 可变与不可变数据结构
- 可变(Mutable): 列表、集合、字典
- 不可变(Immutable): 元组、字符串、数字(int、float)
7. 数据结构的嵌套
可数据结构的嵌套使用,例如列表中嵌套列表、字典中嵌套字典等
python
# 嵌套列表
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list[1][2]) # 输出: 6
# 嵌套字典
nested_dict = {
'person1': {'name': 'Alice', 'age': 25},
'person2': {'name': 'Bob', 'age': 30}
}
print(nested_dict['person1']['name']) # 输出: Alice