目录
一、线性表
总结
二、栈
三、队列
四、哈希表
五、字符串
六、正则表达式
综合示例
一、线性表
线性表(通常用列表表示)是一种按线性顺序存储元素的数据结构。
-
插入元素 (
append,insert) -
删除元素 (
remove,pop) -
查找元素 (
index) -
更新元素 (直接索引访问)
-
遍历元素 (
for循环) -
检查元素存在 (
in运算符) -
获取长度 (
len)
插入元素
-
append: 在列表末尾添加一个元素。1lst = [1, 2, 3]2lst.append(4)3print(lst) # 输出: [1, 2, 3, 4]返回值:
None,操作是原地修改列表。 -
insert: 在指定位置插入一个元素。1lst = [1, 2, 3]2lst.insert(1, 9)3print(lst) # 输出: [1, 9, 2, 3]返回值:
None,操作是原地修改列表。
删除元素
-
remove: 删除第一个匹配的元素。1lst = [1, 2, 3, 2]2lst.remove(2)3print(lst) # 输出: [1, 3, 2]返回值:
None,操作是原地修改列表。如果元素不存在,会引发ValueError。 -
pop: 删除并返回指定位置的元素,默认删除最后一个元素。1lst = [1, 2, 3]2removed_element = lst.pop()3print(lst) # 输出: [1, 2]4print(removed_element) # 输出: 3返回值:被删除的元素。如果列表为空,调用
pop会引发IndexError。
查找元素
-
index: 返回第一个匹配元素的索引。1lst = [1, 2, 3]2idx = lst.index(2)3print(idx) # 输出: 1返回值:匹配元素的索引。如果元素不存在,会引发
ValueError。
更新元素
-
直接索引访问:通过索引更新元素。
1lst = [1, 2, 3]2lst[1] = 93print(lst) # 输出: [1, 9, 3]返回值:
None,操作是原地修改列表。
遍历元素
-
使用
for循环遍历列表中的元素。1lst = [1, 2, 3]2for elem in lst:3print(elem)返回值:
None,只用于遍历和访问元素。
检查元素存在
-
使用
in运算符检查元素是否存在于列表中。1lst = [1, 2, 3]2is_in_list = 2 in lst3print(is_in_list) # 输出: True返回值:布尔值,表示元素是否存在。
获取长度
-
使用
len函数获取列表长度。1lst = [1, 2, 3]2length = len(lst)3print(length) # 输出: 3返回值:整数,表示列表的长度。
总结
以下是一个包含所有操作的示例代码:
|
| lst = [1, 2, 3] |
|
| |
|
| # 插入元素 |
|
| lst.append(4) # 返回值: None |
|
| lst.insert(1, 9) # 返回值: None |
|
| print(lst) # 输出: [1, 9, 2, 3, 4] |
|
| |
|
| # 删除元素 |
|
| lst.remove(2) # 返回值: None |
|
| print(lst) # 输出: [1, 9, 3, 4] |
|
| removed_element = lst.pop() # 返回值: 4 |
|
| print(lst) # 输出: [1, 9, 3] |
|
| print(removed_element) # 输出: 4 |
|
| |
|
| # 查找元素 |
|
| idx = lst.index(9) # 返回值: 1 |
|
| print(idx) # 输出: 1 |
|
| |
|
| # 更新元素 |
|
| lst[1] = 7 # 返回值: None |
|
| print(lst) # 输出: [1, 7, 3] |
|
| |
|
| # 遍历元素 |
|
| for elem in lst: |
|
| print(elem) |
|
| |
|
| # 检查元素存在 |
|
| is_in_list = 2 in lst # 返回值: False |
|
| print(is_in_list) # 输出: False |
|
| |
|
| # 获取长度 |
|
| length = len(lst) # 返回值: 3 |
|
| print(length) # 输出: 3 |
好的,下面是栈、队列和哈希表的基础操作、其返回值及如何返回的详细介绍。
二、栈
栈(Stack)是一种后进先出(LIFO,Last In First Out)的数据结构。
基础操作及返回值
- 压栈(
push) - 出栈(
pop) - 查看栈顶元素(
peek) - 检查栈是否为空(
is_empty)
栈的操作示例(使用Python列表模拟):
|
| # 初始化栈 |
|
| stack = [] |
|
| |
|
| # 压栈 |
|
| stack.append(1) # 返回值: None |
|
| stack.append(2) # 返回值: None |
|
| stack.append(3) # 返回值: None |
|
| print(stack) # 输出: [1, 2, 3] |
|
| |
|
| # 出栈 |
|
| top_element = stack.pop() # 返回值: 3 |
|
| print(top_element) # 输出: 3 |
|
| print(stack) # 输出: [1, 2] |
|
| |
|
| # 查看栈顶元素 |
|
| top_element = stack[-1] # 返回值: 2 |
|
| print(top_element) # 输出: 2 |
|
| |
|
| # 检查栈是否为空 |
|
| is_empty = len(stack) == 0 # 返回值: False |
|
| print(is_empty) # 输出: False |
三、队列
队列(Queue)是一种先进先出(FIFO,First In First Out)的数据结构。
基础操作及返回值
- 入队(
enqueue) - 出队(
dequeue) - 查看队头元素(
peek) - 检查队列是否为空(
is_empty)
队列的操作示例(使用Python的collections.deque):
|
| from collections import deque |
|
| |
|
| # 初始化队列 |
|
| queue = deque() |
|
| |
|
| # 入队 |
|
| queue.append(1) # 返回值: None |
|
| queue.append(2) # 返回值: None |
|
| queue.append(3) # 返回值: None |
|
| print(queue) # 输出: deque([1, 2, 3]) |
|
| |
|
| # 出队 |
|
| front_element = queue.popleft() # 返回值: 1 |
|
| print(front_element) # 输出: 1 |
|
| print(queue) # 输出: deque([2, 3]) |
|
| |
|
| # 查看队头元素 |
|
| front_element = queue[0] # 返回值: 2 |
|
| print(front_element) # 输出: 2 |
|
| |
|
| # 检查队列是否为空 |
|
| is_empty = len(queue) == 0 # 返回值: False |
|
| print(is_empty) # 输出: False |
四、哈希表
哈希表(Hash Table)是一种通过键(Key)直接访问值(Value)的数据结构。在Python中,哈希表由dict(字典)来实现。
基础操作及返回值
- 插入/更新元素(
setitem) - 删除元素(
delitem) - 查找元素(
getitem) - 检查键是否存在(
contains) - 遍历元素(
items)
哈希表的操作示例:
|
| # 初始化哈希表 |
|
| hash_table = { |
|
| "apple": 3, |
|
| "banana": 5, |
|
| "cherry": 7 |
|
| } |
|
| |
|
| # 插入/更新元素 |
|
| hash_table["date"] = 9 # 返回值: None |
|
| hash_table["banana"] = 6 # 返回值: None |
|
| print(hash_table) # 输出: {'apple': 3, 'banana': 6, 'cherry': 7, 'date': 9} |
|
| |
|
| # 删除元素 |
|
| del hash_table["cherry"] # 返回值: None |
|
| print(hash_table) # 输出: {'apple': 3, 'banana': 6, 'date': 9} |
|
| |
|
| # 查找元素 |
|
| value = hash_table.get("apple") # 返回值: 3 |
|
| print(value) # 输出: 3 |
|
| |
|
| # 检查键是否存在 |
|
| key_exists = "banana" in hash_table # 返回值: True |
|
| print(key_exists) # 输出: True |
|
| |
|
| # 遍历元素 |
|
| for key, value in hash_table.items(): |
|
| print(f"Key: {key}, Value: {value}") |
|
| |
|
| # 获取所有键 |
|
| keys = hash_table.keys() # 返回值: dict_keys(['apple', 'banana', 'date']) |
|
| print(keys) # 输出: dict_keys(['apple', 'banana', 'date']) |
|
| |
|
| # 获取所有值 |
|
| values = hash_table.values() # 返回值: dict_values([3, 6, 9]) |
|
| print(values) # 输出: dict_values([3, 6, 9]) |
五、字符串
拼接
- 使用
+运算符或join方法。
|
| # 使用 + 运算符 |
|
| str1 = "Hello" |
|
| str2 = "World" |
|
| result = str1 + " " + str2 |
|
| print(result) # 输出: Hello World |
|
| |
|
| # 使用 join 方法 |
|
| words = ["Hello", "World"] |
|
| result = " ".join(words) |
|
| print(result) # 输出: Hello World |
查找
- 使用
find或index方法。
|
| text = "Hello, World!" |
|
| position = text.find("World") |
|
| print(position) # 输出: 7 |
|
| |
|
| position = text.index("World") |
|
| print(position) # 输出: 7 |
替换
- 使用
replace方法。
|
| text = "Hello, World!" |
|
| new_text = text.replace("World", "there") |
|
| print(new_text) # 输出: Hello, there! |
分割
- 使用
split方法。
|
| text = "apple,banana,cherry" |
|
| fruits = text.split(",") |
|
| print(fruits) # 输出: ['apple', 'banana', 'cherry'] |
去除空白
- 使用
strip,lstrip,rstrip方法。
|
| text = " Hello, World! " |
|
| stripped_text = text.strip() |
|
| print(stripped_text) # 输出: Hello, World! |
大小写转换
- 使用
upper,lower,capitalize,title,swapcase方法。
|
| text = "hello, world!" |
|
| print(text.upper()) # 输出: HELLO, WORLD! |
|
| print(text.lower()) # 输出: hello, world! |
|
| print(text.capitalize()) # 输出: Hello, world! |
|
| print(text.title()) # 输出: Hello, World! |
|
| print(text.swapcase()) # 输出: HELLO, WORLD! |
检查前缀/后缀
- 使用
startswith,endswith方法。
|
| text = "Hello, World!" |
|
| print(text.startswith("Hello")) # 输出: True |
|
| print(text.endswith("World!")) # 输出: True |
格式化
- 使用
format方法或 f-string(Python 3.6+)。
|
| # 使用 format 方法 |
|
| name = "Alice" |
|
| age = 30 |
|
| text = "My name is {} and I am {} years old.".format(name, age) |
|
| print(text) # 输出: My name is Alice and I am 30 years old. |
|
| |
|
| # 使用 f-string |
|
| text = f"My name is {name} and I am {age} years old." |
|
| print(text) # 输出: My name is Alice and I am 30 years old. |
六、正则表达式
正则表达式用于模式匹配和文本处理。Python的 re 模块提供了正则表达式支持。
常用正则表达式操作
- 匹配(
match,search) - 查找所有(
findall) - 替换(
sub) - 分割(
split) - 编译正则表达式(
compile)
匹配
- 使用
match和search方法。
|
| import re |
|
| |
|
| pattern = r"\d+" |
|
| |
|
| # match 从字符串开始位置匹配 |
|
| result = re.match(pattern, "123abc") |
|
| if result: |
|
| print(result.group()) # 输出: 123 |
|
| |
|
| # search 在整个字符串中搜索 |
|
| result = re.search(pattern, "abc123") |
|
| if result: |
|
| print(result.group()) # 输出: 123 |
查找所有
- 使用
findall方法。
|
| text = "abc123xyz456" |
|
| pattern = r"\d+" |
|
| matches = re.findall(pattern, text) |
|
| print(matches) # 输出: ['123', '456'] |
替换
- 使用
sub方法。
|
| text = "abc123xyz456" |
|
| pattern = r"\d+" |
|
| new_text = re.sub(pattern, "#", text) |
|
| print(new_text) # 输出: abc#xyz# |
分割
- 使用
split方法。
|
| text = "one1two2three3four" |
|
| pattern = r"\d" |
|
| parts = re.split(pattern, text) |
|
| print(parts) # 输出: ['one', 'two', 'three', 'four'] |
编译正则表达式
- 使用
compile方法。
|
| pattern = re.compile(r"\d+") |
|
| text = "abc123xyz456" |
|
| matches = pattern.findall(text) |
|
| print(matches) # 输出: ['123', '456'] |
综合示例
|
| import re |
|
| |
|
| # 字符串操作 |
|
| text = " Hello, World! " |
|
| text = text.strip().replace("World", "there").upper() |
|
| print(text) # 输出: HELLO, THERE! |
|
| |
|
| # 正则表达式操作 |
|
| pattern = re.compile(r"\d+") |
|
| text = "abc123xyz456" |
|
| matches = pattern.findall(text) |
|
| print(matches) # 输出: ['123', '456'] |
|
| |
|
| # 替换和分割 |
|
| new_text = re.sub(r"\d+", "#", text) |
|
| print(new_text) # 输出: abc#xyz# |
|
| parts = re.split(r"\d", text) |
|
| print(parts) # 输出: ['abc', '', '', 'xyz', '', '', ''] |