您好,登录后才能下订单哦!
Python3 是一种功能强大的编程语言,提供了丰富的数据结构来帮助开发者高效地处理和组织数据。掌握这些数据结构对于编写高效、可维护的代码至关重要。本文将介绍 Python3 中常用的数据结构及其相关知识点。
列表是 Python 中最常用的数据结构之一,它是一个有序的可变序列,可以存储任意类型的元素。
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 输出: 1
my_list[0] = 10
append()
方法在列表末尾添加元素。
my_list.append(6)
remove()
方法删除指定元素,或使用 pop()
方法删除指定索引的元素。
my_list.remove(10)
my_list.pop(0)
sub_list = my_list[1:3]
元组与列表类似,但元组是不可变的,即一旦创建就不能修改。
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # 输出: 1
a, b, c = my_tuple[:3]
集合是一个无序且不重复的元素集合,常用于去重和集合运算。
my_set = {1, 2, 3, 4, 5}
add()
方法向集合中添加元素。
my_set.add(6)
remove()
方法删除指定元素。
my_set.remove(1)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # 并集
intersection_set = set1 & set2 # 交集
difference_set = set1 - set2 # 差集
字典是一种键值对(key-value)结构,键必须是唯一的,值可以是任意类型。
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict['name']) # 输出: Alice
my_dict['age'] = 26
my_dict['gender'] = 'female'
pop()
方法删除指定键的元素。
my_dict.pop('age')
字符串是不可变的字符序列,常用于文本处理。
my_string = "Hello, World!"
print(my_string[0]) # 输出: H
sub_string = my_string[0:5]
+
操作符拼接字符串。
new_string = my_string + " How are you?"
format()
方法或 f-string 进行字符串格式化。
formatted_string = "Name: {}, Age: {}".format('Alice', 25)
formatted_string_f = f"Name: {'Alice'}, Age: {25}"
栈和队列是两种常用的线性数据结构,Python 中可以使用列表或 collections
模块中的 deque
来实现。
栈是一种后进先出(LIFO)的数据结构。
stack = []
stack.append(1) # 入栈
stack.append(2)
stack.pop() # 出栈,返回 2
队列是一种先进先出(FIFO)的数据结构。
from collections import deque
queue = deque()
queue.append(1) # 入队
queue.append(2)
queue.popleft() # 出队,返回 1
堆是一种特殊的树形数据结构,常用于优先队列的实现。Python 中的 heapq
模块提供了堆操作。
import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
heappop()
方法获取并删除堆中的最小元素。
smallest = heapq.heappop(heap) # 返回 1
heapq.heapify()
方法将列表转换为堆。
heap_list = [3, 1, 2]
heapq.heapify(heap_list)
链表是一种动态数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。Python 中可以使用自定义类来实现链表。
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 创建链表
ll = LinkedList()
ll.head = Node(1)
second = Node(2)
third = Node(3)
ll.head.next = second
second.next = third
current = ll.head
while current:
print(current.data)
current = current.next
new_node = Node(4)
new_node.next = second.next
second.next = new_node
second.next = third.next
树是一种层次化的数据结构,由节点和边组成,每个节点可以有多个子节点。Python 中可以使用自定义类来实现树。
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
# 创建树
root = TreeNode(1)
child1 = TreeNode(2)
child2 = TreeNode(3)
root.children.append(child1)
root.children.append(child2)
dfs(root)
## 10. 图(Graph)
图是由节点和边组成的非线性数据结构,常用于表示网络关系。Python 中可以使用字典或自定义类来实现图。
### 10.1 创建图
```python
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
dfs(graph, ‘A’) “`
Python3 提供了丰富的数据结构,包括列表、元组、集合、字典、字符串、栈、队列、堆、链表、树和图等。掌握这些数据结构及其常用操作,可以帮助开发者更高效地处理和组织数据,编写出高质量的代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。