目錄
一、線性表
總結
二、棧
三、隊列
四、哈希表
五、字符串
六、正則表達式
綜合示例
一、線性表
線性表(通常用列表表示)是一種按線性順序存儲元素的數據結構。
-
插入元素?(
append
,?insert
) -
刪除元素?(
remove
,?pop
) -
查找元素?(
index
) -
更新元素?(直接索引訪問)
-
遍歷元素?(
for
循環) -
檢查元素存在?(
in
運算符) -
獲取長度?(
len
)
插入元素
-
append
: 在列表末尾添加一個元素。1
lst = [1, 2, 3]
2
lst.append(4)
3
print(lst) # 輸出: [1, 2, 3, 4]
返回值:
None
,操作是原地修改列表。 -
insert
: 在指定位置插入一個元素。1
lst = [1, 2, 3]
2
lst.insert(1, 9)
3
print(lst) # 輸出: [1, 9, 2, 3]
返回值:
None
,操作是原地修改列表。
刪除元素
-
remove
: 刪除第一個匹配的元素。1
lst = [1, 2, 3, 2]
2
lst.remove(2)
3
print(lst) # 輸出: [1, 3, 2]
返回值:
None
,操作是原地修改列表。如果元素不存在,會引發ValueError
。 -
pop
: 刪除并返回指定位置的元素,默認刪除最后一個元素。1
lst = [1, 2, 3]
2
removed_element = lst.pop()
3
print(lst) # 輸出: [1, 2]
4
print(removed_element) # 輸出: 3
返回值:被刪除的元素。如果列表為空,調用
pop
會引發IndexError
。
查找元素
-
index
: 返回第一個匹配元素的索引。1
lst = [1, 2, 3]
2
idx = lst.index(2)
3
print(idx) # 輸出: 1
返回值:匹配元素的索引。如果元素不存在,會引發
ValueError
。
更新元素
-
直接索引訪問:通過索引更新元素。
1
lst = [1, 2, 3]
2
lst[1] = 9
3
print(lst) # 輸出: [1, 9, 3]
返回值:
None
,操作是原地修改列表。
遍歷元素
-
使用
for
循環遍歷列表中的元素。1
lst = [1, 2, 3]
2
for elem in lst:
3
print(elem)
返回值:
None
,只用于遍歷和訪問元素。
檢查元素存在
-
使用
in
運算符檢查元素是否存在于列表中。1
lst = [1, 2, 3]
2
is_in_list = 2 in lst
3
print(is_in_list) # 輸出: True
返回值:布爾值,表示元素是否存在。
獲取長度
-
使用
len
函數獲取列表長度。1
lst = [1, 2, 3]
2
length = len(lst)
3
print(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', '', '', ''] |