Python 数据结构和算法简介
[
](https://res.cloudinary.com/practicaldev/image/fetch/s--uPs1RSdw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/lv7qu1jxc7weygwqqe1f.jpg)
数据结构是数据值、它们之间的关系以及可应用于数据的函数或操作的集合。
数据结构允许您_组织_您的数据,使您能够_存储_数据集合、关联_它们并相应地_执行操作。
数据算法是一组定义明确的指令,用于解决特定问题。它需要一组输入并产生所需的输出。
数据结构的类型
[
](https://res.cloudinary.com/practicaldev/image/fetch/s--l1SGIehx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/i2q33q0e052aw9mcs84y.png)
1\。清单
这是一个 ordered 和 changeable 的项目集合,它还允许重复项目。它可以包含不同的数据类型。
列表是通过 方括号[] 或 list() 构造函数创建的。
例如:
my_list=["melon","apple","mango"]
进入全屏模式 退出全屏模式
列出方法
Python 有一组可用于列表的内置方法。
#access a list item
print(my_list[2])
#append() Adds an element at the end of the list
my_list.append("orange")
#clear() Removes all the elements from the list
my_list.clear()
#copy() Returns a copy of the list
my_list.copy()
#extend()Adds list items to the end of the current list
my_list.extend(another_list)
#insert() Adds an element at the specified position\index
my_list.insert(3,"guava")
#pop() Removes the element at the specified position\index
my_list.pop(1)
#remove() Removes the item with the specified value
my_list.remove("apple")
#reverse() Reverses the order of the list
my_list.reverse()
#sort() Sorts the list alphanumerically, ascending, by default
my_list.sort()
进入全屏模式 退出全屏模式
2\。元组
这些是允许重复的不可更改、有序数据结构。
它们是通过 () 或 tuple() 构造函数创建的。
#create a tuple
number=(45,34,678)
#access a tuple item
number[0]
#delete a tuple
del number
进入全屏模式 退出全屏模式
一旦你创建了一个元组,你就不能改变它,也就是说你不能添加、编辑或删除其中的任何项目。除非您将其更改为可变数据结构(例如列表),然后再改回元组。
y=list(number)
#add the list method you want performed e.g sort()
y.sort()
number=tuple(y)
进入全屏模式 退出全屏模式
3\。字典
字典用于将数据值存储在键:值对中。
它们是可变的,不允许重复键,并且用大括号 {} 书写
dog = {'name':'Cara',
'color':'Brown',
'gender':'Female'}
进入全屏模式 退出全屏模式
字典方法
#keys() prints out all the keys
for i in dog.keys():
print(i)
#values() prints out all the values
for i in dog.values():
print(i)
#items() prints out the key:value pair
for i in dog.items():
print(i)
进入全屏模式 退出全屏模式
输出
name
color
gender
Cara
Brown
Female
('name', 'Cara')
('color', 'Brown')
('gender', 'Female')
进入全屏模式 退出全屏模式
在访问该键的值之前检查该键是否存在于字典中是很乏味的。幸运的是,字典有一个 get() 方法,它接受两个参数:要检索的值的键和如果该键不存在则返回的备用值。
print(dog.get('sound',0))
进入全屏模式 退出全屏模式
输出
0
进入全屏模式 退出全屏模式
4\。套
与字典不同,集合是不可更改的,而且不支持重复。
myset = {"apple", "banana", "cherry"}
进入全屏模式 退出全屏模式
5\。堆栈
stack 是遵循后进先出 (LIFO) 原则的线性数据结构。这意味着插入堆栈中的最后一个元素首先被删除。
在编程术语中,将一个项目放在堆栈顶部称为push,而删除一个项目称为pop。
[
](https://res.cloudinary.com/practicaldev/image/fetch/s--j9Ixsam5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/5k7zfnu0mhx1zihfltcc.png)
# Creating a stack
def create_stack():
stack = []
return stack
# Creating an empty stack
def check_empty(stack):
return len(stack) == 0
# Adding items into the stack
def push(stack, item):
stack.append(item)
print("pushed item: " + item)
# Removing an element from the stack
def pop(stack):
if (check_empty(stack)):
return "stack is empty"
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
进入全屏模式 退出全屏模式
输出
pushed item: 1
pushed item: 2
pushed item: 3
pushed item: 4
popped item: 4
stack after popping an element: ['1', '2', '3']
进入全屏模式 退出全屏模式
6\。尾巴
queue 是一种线性类型的数据结构,用于按顺序存储数据,它遵循先进先出 (FIFO) 规则 - 首先进入的项目是最先出来的项目。
Enqueue 正在向队列末尾添加一个元素,而
Dequeue 正在从队列的前面移除一个元素。
[
](https://res.cloudinary.com/practicaldev/image/fetch/s--dlToehNW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/7vvox5yx3zazur7i4g78.png)
# Queue implementation in Python
class Queue:
def __init__(self):
self.queue = []
# Add an element
def enqueue(self, item):
self.queue.append(item)
# Remove an element
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
# Display the queue
def display(self):
print(self.queue)
def size(self):
return len(self.queue)
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.display()
q.dequeue()
print("After removing an element")
q.display()
进入全屏模式 退出全屏模式
输出
[1, 2, 3, 4, 5]
After removing an element
[2, 3, 4, 5]
进入全屏模式 退出全屏模式
7\。链接列表
链表是包含一系列连接节点的线性数据结构。每个节点存储数据和下一个节点的地址。
第一个节点称为head,它被用作列表中任何迭代的起点。最后一个节点的 next 引用必须指向 None 以确定列表的结尾。这是它的外观:
[
](https://res.cloudinary.com/practicaldev/image/fetch/s--eTnBhGmZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/dln3dsnoj0qbto7gssje.png)
# Linked list implementation in Python
class Node:
# Creating a node
def __init__(self, item):
self.item = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
if __name__ == '__main__':
linked_list = LinkedList()
# Assign item values
linked_list.head = Node(1)
second = Node(2)
third = Node(3)
# Connect nodes
linked_list.head.next = second
second.next = third
# Print the linked list item
while linked_list.head != None:
print(linked_list.head.item, end=" ")
linked_list.head = linked_list.head.next
进入全屏模式 退出全屏模式
输出
1 2 3
进入全屏模式 退出全屏模式
那么是什么让它们与普通列表不同呢?链表与列表的不同之处在于它们在内存中存储元素的方式。虽然列表使用连续的内存块来存储对其数据的引用,但链表将引用存储为它们自己元素的一部分。
上面的概念可能是压倒性的,所以慢慢来。
编码快乐!!_
更多推荐

所有评论(0)