2022年 11月 5日

Python中的数据结构

        在任何语言中,数据结构都用于存储和操作复杂的数据。 在 Python 中,数据结构是一种存储容器,可以有效地管理、组织和搜索数据。 它们用于存储一组称为集合的数据元素,需要一起存储和处理。 在 Python 中,有五种不同的数据结构可用于存储集合。

一、列表(Lists)

        有序的可变元素序列。

        在 Python 中,列表是用于存储可变元素序列的主要数据结构。 存储在列表中的数据元素序列不必是同一类型。

要创建列表,数据元素需要包含在 [ ] 中,并且需要用逗号分隔。 例如,以下代码一起创建了四个不同类型的数据元素。

  1. aList = ["John", 33,"Toronto", True]
  2. type(aList)

1、切片

        通过指定索引范围可以检索列表中的元素子集,这个过程叫作切片。

bin_colors=['Red','Green','Blue','Yellow']

        查看如下示例 

  1. bin_colors[0:2]
  2. #会输出['Red', 'Green']
  1. bin_colors[1]
  2. #会输出'Green'
  1. bin_colors[2:]
  2. #会输出['Blue', 'Yellow']
  1. bin_colors[:2]
  2. #会输出['Red', 'Green']

2、负索引

        负索引从列表的末尾开始计数。

        查看如下示例

  1. bin_colors[:-1]
  2. #['Red', 'Green', 'Blue']
  3. bin_colors[:-2]
  4. #['Red', 'Green']
  5. bin_colors[-2:-1]
  6. #['Blue']

3、嵌套

        列表的元素可以是简单数据类型或复杂数据类型。 这允许嵌套在列表中。 对于迭代和递归算法,这提供了重要的功能。

        查看如下示例

  1. a = [1,2,[100,200,300],6]
  2. max(a[2])
  3. #300
  4. a[2][1]
  5. #200

4、迭代

  1. for aColor in bin_colors:
  2. print(aColor+ " Square")
  3. #Red Square
  4. #Green Square
  5. #Blue Square
  6. #Yellow Square

5、Lambda

        lambda 函数可用于列表。 它们在算法的上下文中特别重要,并提供了动态创建函数的能力。 它们也被称为匿名函数。

        过滤数据

  1. list(filter(lambda x: x > 100, [-5, 200, 300, -10, 10, 1000]))
  2. #[200, 300, 1000]

        数据转换

  1. list(map(lambda x: x ** 2, [11, 22, 33, 44,55]))
  2. #[121, 484, 1089, 1936, 3025]

        数据聚合

        对于数据聚合,可以使用 reduce() 函数,它递归地运行一个函数来处理列表每个元素上的值对。

  1. from functools import reduce
  2. def doSum(x1,x2):
  3. return x1+x2
  4. x = reduce(doSum, [100, 122, 33, 4, 5, 6])
  5. print (f"数据聚合 is {x}")
  6. #数据聚合 is 270

        范围功能

        range 函数可用于轻松生成大量数字列表。 它用于自动填充列表中的数字序列。

        range 函数使用起来很简单。 我们可以通过指定列表中我们想要的元素数量来使用它。 默认情况下,它从零开始并递增一。

二、元组(Tuples)

        有序的不可变元素序列。

        可用于存储集合的第二种数据结构是元组。 与列表相反,元组是不可变(只读)的数据结构。 元组由 ( ) 包围的几个元素组成。

        像列表一样,元组中的元素可以是不同的类型。 它们还允许其元素使用复杂的数据类型。 所以元组中可以有一个元组,提供一种创建嵌套数据结构的方法。 创建嵌套数据结构的能力在迭代和递归算法中特别有用。

        以下代码演示了如何创建元组

  1. bin_colors=('Red','Green','Blue','Yellow')
  2. print(f"The second element of the tuple is {bin_colors[1]}")
  3. #The second element of the tuple is Green
  4. print(f"The elements after thrid element onwards are {bin_colors[2:]}")
  5. #The elements after thrid element onwards are ('Blue', 'Yellow')
  6. nested_tuple = (1,2,(100,200,300),6)
  7. print(f"The maximum value of the inner tuple {max(nested_tuple[2])}")
  8. #The maximum value of the inner tuple 300

三、字典(dictionary)

        无序的键值对序列。

        创建一个简单的字典,将颜色分配给各种变量,键值对需要包含在 {} 中。 例如,以下代码创建一个由三个键值对组成的简单字典:

  1. bin_colors ={
  2. "manual_color": "Yellow",
  3. "approved_color": "Green",
  4. "refused_color": "Red"
  5. }
  6. print(bin_colors)
  7. #{'manual_color': 'Yellow', 'approved_color': 'Green', 'refused_color': 'Red'}

        获取和赋值

  1. bin_colors.get('approved_color')
  2. #'Green'
  3. bin_colors['approved_color']
  4. #'Green'
  5. bin_colors['approved_color']="Purple"
  6. print(bin_colors)
  7. #{'manual_color': 'Yellow', 'approved_color': 'Purple', 'refused_color': 'Red'}

四、集合(Set)

        无序元素序列(其中元素不重复)。

        集合被定义为可以是不同类型的元素的集合。 元素用 { } 括起来。 例如,看看下面的代码块:

  1. green = {'grass', 'leaves'}
  2. print(green)
  3. #{'leaves', 'grass'}
  4. yellow = {'dandelions', 'fire hydrant', 'leaves'}
  5. red = {'fire hydrant', 'blood', 'rose', 'leaves'}
  6. print(f"The union of yellow and red sets is {yellow|red}")
  7. #The union of yellow and red sets is {'rose', 'dandelions', 'blood', 'fire hydrant', 'leaves'}
  8. print(f"The intersaction of yellow and red is {yellow&red}")
  9. #The intersaction of yellow and red is {'fire hydrant', 'leaves'}

五、数据帧(DataFrame)

        存储二维数据的二维结构。       

        DataFrame 是一种数据结构,用于存储 Python 的 pandas 包中可用的表格数据。 它是算法最重要的数据结构之一,用于处理传统的结构化数据。

        可以使用以下代码创建一个简单的 DataFrame。

  1. import pandas as pd
  2. df = pd.DataFrame([
  3. ['1', 'Fares', 32, True],
  4. ['2', 'Elena', 23, False],
  5. ['3', 'Steven', 40, True]])
  6. df.columns = ['id', 'name', 'age', 'decision']
  7. 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 的类,我们将在其中定义与堆栈类相关的所有操作。 这个类的代码如下:

  1. class Stack:
  2. def __init__(self):
  3. self.items = []
  4. def isEmpty(self):
  5. return self.items == []
  6. def push(self, item):
  7. self.items.append(item)
  8. def pop(self):
  9. return self.items.pop()
  10. def peek(self):
  11. return self.items[len(self.items)-1]
  12. def size(self):
  13. return len(self.items)

        要将四个元素压入堆栈,可以使用以下代码:

  1. stack=Stack()
  2. stack.push('Red')
  3. stack.push('Green')
  4. stack.push("Blue")
  5. stack.push("Yellow")
  1. stack.pop()
  2. #'Yellow'
  1. stack.isEmpty()
  2. #False

2、Queue

        与栈一样,队列将 n 个元素存储在一维结构中。 元素以先进先出 (FIFO) 格式添加和删除。 队列的一端称为后端,另一端称为前端。 元素从前面移除,这个操作称为出队。 元素添加在后面,操作称为入队。

        上图中的队列可以使用如下代码实现:

  1. class Queue(object):
  2. def __init__(self):
  3. self.items = []
  4. def isEmpty(self):
  5. return self.items == []
  6. def enqueue(self, item):
  7. self.items.insert(0,item)
  8. def dequeue(self):
  9. return self.items.pop()
  10. def size(self):
  11. return len(self.items)
  12. queue = Queue()
  13. queue.enqueue("Red")
  14. queue.enqueue('Green')
  15. queue.enqueue('Blue')
  16. queue.enqueue('Yellow')
  17. print(f"Size of queue is {queue.size()}")
  18. #Size of queue is 4
  19. print(queue.dequeue())
  20. #Red