在任何语言中,数据结构都用于存储和操作复杂的数据。 在 Python 中,数据结构是一种存储容器,可以有效地管理、组织和搜索数据。 它们用于存储一组称为集合的数据元素,需要一起存储和处理。 在 Python 中,有五种不同的数据结构可用于存储集合。
一、列表(Lists)
有序的可变元素序列。
在 Python 中,列表是用于存储可变元素序列的主要数据结构。 存储在列表中的数据元素序列不必是同一类型。
要创建列表,数据元素需要包含在 [ ] 中,并且需要用逗号分隔。 例如,以下代码一起创建了四个不同类型的数据元素。
- aList = ["John", 33,"Toronto", True]
- type(aList)
1、切片
通过指定索引范围可以检索列表中的元素子集,这个过程叫作切片。
bin_colors=['Red','Green','Blue','Yellow']
查看如下示例
- bin_colors[0:2]
- #会输出['Red', 'Green']
- bin_colors[1]
- #会输出'Green'
- bin_colors[2:]
- #会输出['Blue', 'Yellow']
- bin_colors[:2]
- #会输出['Red', 'Green']
2、负索引
负索引从列表的末尾开始计数。
查看如下示例
- bin_colors[:-1]
- #['Red', 'Green', 'Blue']
-
- bin_colors[:-2]
- #['Red', 'Green']
-
- bin_colors[-2:-1]
- #['Blue']
3、嵌套
列表的元素可以是简单数据类型或复杂数据类型。 这允许嵌套在列表中。 对于迭代和递归算法,这提供了重要的功能。
查看如下示例
- a = [1,2,[100,200,300],6]
- max(a[2])
- #300
-
- a[2][1]
- #200
4、迭代
- for aColor in bin_colors:
- print(aColor+ " Square")
-
- #Red Square
- #Green Square
- #Blue Square
- #Yellow Square
5、Lambda
lambda 函数可用于列表。 它们在算法的上下文中特别重要,并提供了动态创建函数的能力。 它们也被称为匿名函数。
过滤数据
- list(filter(lambda x: x > 100, [-5, 200, 300, -10, 10, 1000]))
- #[200, 300, 1000]
数据转换
- list(map(lambda x: x ** 2, [11, 22, 33, 44,55]))
- #[121, 484, 1089, 1936, 3025]
数据聚合
对于数据聚合,可以使用 reduce() 函数,它递归地运行一个函数来处理列表每个元素上的值对。
- from functools import reduce
- def doSum(x1,x2):
- return x1+x2
- x = reduce(doSum, [100, 122, 33, 4, 5, 6])
- print (f"数据聚合 is {x}")
-
- #数据聚合 is 270
范围功能
range 函数可用于轻松生成大量数字列表。 它用于自动填充列表中的数字序列。
range 函数使用起来很简单。 我们可以通过指定列表中我们想要的元素数量来使用它。 默认情况下,它从零开始并递增一。
二、元组(Tuples)
有序的不可变元素序列。
可用于存储集合的第二种数据结构是元组。 与列表相反,元组是不可变(只读)的数据结构。 元组由 ( ) 包围的几个元素组成。
像列表一样,元组中的元素可以是不同的类型。 它们还允许其元素使用复杂的数据类型。 所以元组中可以有一个元组,提供一种创建嵌套数据结构的方法。 创建嵌套数据结构的能力在迭代和递归算法中特别有用。
以下代码演示了如何创建元组
- bin_colors=('Red','Green','Blue','Yellow')
- print(f"The second element of the tuple is {bin_colors[1]}")
- #The second element of the tuple is Green
-
- print(f"The elements after thrid element onwards are {bin_colors[2:]}")
- #The elements after thrid element onwards are ('Blue', 'Yellow')
-
-
- nested_tuple = (1,2,(100,200,300),6)
- print(f"The maximum value of the inner tuple {max(nested_tuple[2])}")
- #The maximum value of the inner tuple 300
三、字典(dictionary)
无序的键值对序列。
创建一个简单的字典,将颜色分配给各种变量,键值对需要包含在 {} 中。 例如,以下代码创建一个由三个键值对组成的简单字典:
- bin_colors ={
- "manual_color": "Yellow",
- "approved_color": "Green",
- "refused_color": "Red"
- }
- print(bin_colors)
- #{'manual_color': 'Yellow', 'approved_color': 'Green', 'refused_color': 'Red'}
获取和赋值
- bin_colors.get('approved_color')
- #'Green'
-
- bin_colors['approved_color']
- #'Green'
-
- bin_colors['approved_color']="Purple"
- print(bin_colors)
- #{'manual_color': 'Yellow', 'approved_color': 'Purple', 'refused_color': 'Red'}
四、集合(Set)
无序元素序列(其中元素不重复)。
集合被定义为可以是不同类型的元素的集合。 元素用 { } 括起来。 例如,看看下面的代码块:
- green = {'grass', 'leaves'}
- print(green)
- #{'leaves', 'grass'}
-
- yellow = {'dandelions', 'fire hydrant', 'leaves'}
- red = {'fire hydrant', 'blood', 'rose', 'leaves'}
- print(f"The union of yellow and red sets is {yellow|red}")
- #The union of yellow and red sets is {'rose', 'dandelions', 'blood', 'fire hydrant', 'leaves'}
-
- print(f"The intersaction of yellow and red is {yellow&red}")
- #The intersaction of yellow and red is {'fire hydrant', 'leaves'}
五、数据帧(DataFrame)
存储二维数据的二维结构。
DataFrame 是一种数据结构,用于存储 Python 的 pandas 包中可用的表格数据。 它是算法最重要的数据结构之一,用于处理传统的结构化数据。
可以使用以下代码创建一个简单的 DataFrame。
- import pandas as pd
- df = pd.DataFrame([
- ['1', 'Fares', 32, True],
- ['2', 'Elena', 23, False],
- ['3', 'Steven', 40, True]])
- df.columns = ['id', 'name', 'age', 'decision']
- print(df)
id name age decision 0 1 Fares 32 True 1 2 Elena 23 False 2 3 Steven 40 True
1、选择列
df[['name','age']]
列的位置在数据框中是确定的。 第四列可以通过它的位置来检索,如下所示:
df.iloc[:,3]
0 True
1 False
2 True
Name: decision, dtype: bool
2、选择行
df.iloc[1:3,:]
df[df.age>30]
df[(df.age<35)&(df.decision==True)]
六、Stack和Queue
1、Stack
堆栈是一种线性数据结构,用于存储一维列表。 它可以以后进先出 (LIFO) 或先进后出 (FILO) 方式存储项目。 堆栈的定义特征是从其中添加和删除元素的方式。 在一端添加一个新元素,仅从该端删除一个元素。
以下是与堆栈相关的操作:
isEmpty:如果堆栈为空,则返回 true push:添加一个新元素。 pop:它返回最近添加的元素并将其删除。
让我们在 Python 中创建一个名为 Stack 的类,我们将在其中定义与堆栈类相关的所有操作。 这个类的代码如下:
- class Stack:
- def __init__(self):
- self.items = []
- def isEmpty(self):
- return self.items == []
- def push(self, item):
- self.items.append(item)
- def pop(self):
- return self.items.pop()
- def peek(self):
- return self.items[len(self.items)-1]
- def size(self):
- return len(self.items)
要将四个元素压入堆栈,可以使用以下代码:
- stack=Stack()
- stack.push('Red')
- stack.push('Green')
- stack.push("Blue")
- stack.push("Yellow")
- stack.pop()
- #'Yellow'
- stack.isEmpty()
- #False
2、Queue
与栈一样,队列将 n 个元素存储在一维结构中。 元素以先进先出 (FIFO) 格式添加和删除。 队列的一端称为后端,另一端称为前端。 元素从前面移除,这个操作称为出队。 元素添加在后面,操作称为入队。
上图中的队列可以使用如下代码实现:
- class Queue(object):
- def __init__(self):
- self.items = []
- def isEmpty(self):
- return self.items == []
- def enqueue(self, item):
- self.items.insert(0,item)
- def dequeue(self):
- return self.items.pop()
- def size(self):
- return len(self.items)
-
- queue = Queue()
- queue.enqueue("Red")
- queue.enqueue('Green')
- queue.enqueue('Blue')
- queue.enqueue('Yellow')
-
- print(f"Size of queue is {queue.size()}")
- #Size of queue is 4
-
- print(queue.dequeue())
- #Red