Python基础知识归纳总结

目录

一、线性表

总结

二、栈

三、队列

四、哈希表

五、字符串

六、正则表达式

综合示例


一、线性表

线性表(通常用列表表示)是一种按线性顺序存储元素的数据结构。

  1. 插入元素 (appendinsert)

  2. 删除元素 (removepop)

  3. 查找元素 (index)

  4. 更新元素 (直接索引访问)

  5. 遍历元素 (for循环)

  6. 检查元素存在 (in运算符)

  7. 获取长度 (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

    返回值:整数,表示列表的长度。

总结

以下是一个包含所有操作的示例代码:

1

lst = [1, 2, 3]

2

3

# 插入元素

4

lst.append(4) # 返回值: None

5

lst.insert(1, 9) # 返回值: None

6

print(lst) # 输出: [1, 9, 2, 3, 4]

7

8

# 删除元素

9

lst.remove(2) # 返回值: None

10

print(lst) # 输出: [1, 9, 3, 4]

11

removed_element = lst.pop() # 返回值: 4

12

print(lst) # 输出: [1, 9, 3]

13

print(removed_element) # 输出: 4

14

15

# 查找元素

16

idx = lst.index(9) # 返回值: 1

17

print(idx) # 输出: 1

18

19

# 更新元素

20

lst[1] = 7 # 返回值: None

21

print(lst) # 输出: [1, 7, 3]

22

23

# 遍历元素

24

for elem in lst:

25

print(elem)

26

27

# 检查元素存在

28

is_in_list = 2 in lst # 返回值: False

29

print(is_in_list) # 输出: False

30

31

# 获取长度

32

length = len(lst) # 返回值: 3

33

print(length) # 输出: 3

好的,下面是栈、队列和哈希表的基础操作、其返回值及如何返回的详细介绍。

二、栈

栈(Stack)是一种后进先出(LIFO,Last In First Out)的数据结构。

基础操作及返回值

  1. 压栈(push
  2. 出栈(pop
  3. 查看栈顶元素(peek
  4. 检查栈是否为空(is_empty

栈的操作示例(使用Python列表模拟):

1

# 初始化栈

2

stack = []

3

4

# 压栈

5

stack.append(1) # 返回值: None

6

stack.append(2) # 返回值: None

7

stack.append(3) # 返回值: None

8

print(stack) # 输出: [1, 2, 3]

9

10

# 出栈

11

top_element = stack.pop() # 返回值: 3

12

print(top_element) # 输出: 3

13

print(stack) # 输出: [1, 2]

14

15

# 查看栈顶元素

16

top_element = stack[-1] # 返回值: 2

17

print(top_element) # 输出: 2

18

19

# 检查栈是否为空

20

is_empty = len(stack) == 0 # 返回值: False

21

print(is_empty) # 输出: False

三、队列

队列(Queue)是一种先进先出(FIFO,First In First Out)的数据结构。

基础操作及返回值

  1. 入队(enqueue
  2. 出队(dequeue
  3. 查看队头元素(peek
  4. 检查队列是否为空(is_empty

队列的操作示例(使用Python的collections.deque):

1

from collections import deque

2

3

# 初始化队列

4

queue = deque()

5

6

# 入队

7

queue.append(1) # 返回值: None

8

queue.append(2) # 返回值: None

9

queue.append(3) # 返回值: None

10

print(queue) # 输出: deque([1, 2, 3])

11

12

# 出队

13

front_element = queue.popleft() # 返回值: 1

14

print(front_element) # 输出: 1

15

print(queue) # 输出: deque([2, 3])

16

17

# 查看队头元素

18

front_element = queue[0] # 返回值: 2

19

print(front_element) # 输出: 2

20

21

# 检查队列是否为空

22

is_empty = len(queue) == 0 # 返回值: False

23

print(is_empty) # 输出: False

四、哈希表

哈希表(Hash Table)是一种通过键(Key)直接访问值(Value)的数据结构。在Python中,哈希表由dict(字典)来实现。

基础操作及返回值

  1. 插入/更新元素(setitem
  2. 删除元素(delitem
  3. 查找元素(getitem
  4. 检查键是否存在(contains
  5. 遍历元素(items

哈希表的操作示例:

1

# 初始化哈希表

2

hash_table = {

3

"apple": 3,

4

"banana": 5,

5

"cherry": 7

6

}

7

8

# 插入/更新元素

9

hash_table["date"] = 9 # 返回值: None

10

hash_table["banana"] = 6 # 返回值: None

11

print(hash_table) # 输出: {'apple': 3, 'banana': 6, 'cherry': 7, 'date': 9}

12

13

# 删除元素

14

del hash_table["cherry"] # 返回值: None

15

print(hash_table) # 输出: {'apple': 3, 'banana': 6, 'date': 9}

16

17

# 查找元素

18

value = hash_table.get("apple") # 返回值: 3

19

print(value) # 输出: 3

20

21

# 检查键是否存在

22

key_exists = "banana" in hash_table # 返回值: True

23

print(key_exists) # 输出: True

24

25

# 遍历元素

26

for key, value in hash_table.items():

27

print(f"Key: {key}, Value: {value}")

28

29

# 获取所有键

30

keys = hash_table.keys() # 返回值: dict_keys(['apple', 'banana', 'date'])

31

print(keys) # 输出: dict_keys(['apple', 'banana', 'date'])

32

33

# 获取所有值

34

values = hash_table.values() # 返回值: dict_values([3, 6, 9])

35

print(values) # 输出: dict_values([3, 6, 9])

五、字符串

拼接

  • 使用 + 运算符或 join 方法。

1

# 使用 + 运算符

2

str1 = "Hello"

3

str2 = "World"

4

result = str1 + " " + str2

5

print(result) # 输出: Hello World

6

7

# 使用 join 方法

8

words = ["Hello", "World"]

9

result = " ".join(words)

10

print(result) # 输出: Hello World

查找

  • 使用 find 或 index 方法。

1

text = "Hello, World!"

2

position = text.find("World")

3

print(position) # 输出: 7

4

5

position = text.index("World")

6

print(position) # 输出: 7

替换

  • 使用 replace 方法。

1

text = "Hello, World!"

2

new_text = text.replace("World", "there")

3

print(new_text) # 输出: Hello, there!

分割

  • 使用 split 方法。

1

text = "apple,banana,cherry"

2

fruits = text.split(",")

3

print(fruits) # 输出: ['apple', 'banana', 'cherry']

去除空白

  • 使用 striplstriprstrip 方法。

1

text = " Hello, World! "

2

stripped_text = text.strip()

3

print(stripped_text) # 输出: Hello, World!

大小写转换

  • 使用 upperlowercapitalizetitleswapcase 方法。

1

text = "hello, world!"

2

print(text.upper()) # 输出: HELLO, WORLD!

3

print(text.lower()) # 输出: hello, world!

4

print(text.capitalize()) # 输出: Hello, world!

5

print(text.title()) # 输出: Hello, World!

6

print(text.swapcase()) # 输出: HELLO, WORLD!

检查前缀/后缀

  • 使用 startswithendswith 方法。

1

text = "Hello, World!"

2

print(text.startswith("Hello")) # 输出: True

3

print(text.endswith("World!")) # 输出: True

格式化

  • 使用 format 方法或 f-string(Python 3.6+)。

1

# 使用 format 方法

2

name = "Alice"

3

age = 30

4

text = "My name is {} and I am {} years old.".format(name, age)

5

print(text) # 输出: My name is Alice and I am 30 years old.

6

7

# 使用 f-string

8

text = f"My name is {name} and I am {age} years old."

9

print(text) # 输出: My name is Alice and I am 30 years old.

六、正则表达式

正则表达式用于模式匹配和文本处理。Python的 re 模块提供了正则表达式支持。

常用正则表达式操作

  1. 匹配(matchsearch
  2. 查找所有(findall
  3. 替换(sub
  4. 分割(split
  5. 编译正则表达式(compile

匹配

  • 使用 match 和 search 方法。

1

import re

2

3

pattern = r"\d+"

4

5

# match 从字符串开始位置匹配

6

result = re.match(pattern, "123abc")

7

if result:

8

print(result.group()) # 输出: 123

9

10

# search 在整个字符串中搜索

11

result = re.search(pattern, "abc123")

12

if result:

13

print(result.group()) # 输出: 123

查找所有

  • 使用 findall 方法。

1

text = "abc123xyz456"

2

pattern = r"\d+"

3

matches = re.findall(pattern, text)

4

print(matches) # 输出: ['123', '456']

替换

  • 使用 sub 方法。

1

text = "abc123xyz456"

2

pattern = r"\d+"

3

new_text = re.sub(pattern, "#", text)

4

print(new_text) # 输出: abc#xyz#

分割

  • 使用 split 方法。

1

text = "one1two2three3four"

2

pattern = r"\d"

3

parts = re.split(pattern, text)

4

print(parts) # 输出: ['one', 'two', 'three', 'four']

编译正则表达式

  • 使用 compile 方法。

1

pattern = re.compile(r"\d+")

2

text = "abc123xyz456"

3

matches = pattern.findall(text)

4

print(matches) # 输出: ['123', '456']

综合示例

1

import re

2

3

# 字符串操作

4

text = " Hello, World! "

5

text = text.strip().replace("World", "there").upper()

6

print(text) # 输出: HELLO, THERE!

7

8

# 正则表达式操作

9

pattern = re.compile(r"\d+")

10

text = "abc123xyz456"

11

matches = pattern.findall(text)

12

print(matches) # 输出: ['123', '456']

13

14

# 替换和分割

15

new_text = re.sub(r"\d+", "#", text)

16

print(new_text) # 输出: abc#xyz#

17

parts = re.split(r"\d", text)

18

print(parts) # 输出: ['abc', '', '', 'xyz', '', '', '']

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值