python 堆栈

In our previous tutorial we learned about Python signal processing. In this tutorial we will learn about python stack.

在上一教程中,我们了解了Python信号处理 。 在本教程中,我们将学习python堆栈。

Python堆栈 (Python Stack)

To start with this tutorial, you have to know what is stack at first. Basically stack is Last-In-First-Out data structure. That means, the item that entered last in the system will be removed at first.

要开始本教程,您首先必须知道什么是堆栈。 基本上,堆栈是后进先出数据结构。 这意味着,系统中最后输入的项目将首先被删除。

For example, let’s say you have a pipe with only one open end. And you have some balls that fit just fine in the pipe. So when you will insert these balls in the pipe, they will get stacked on top of each other. However when you will remove the balls, the last one will be removed first.

例如,假设您的管道只有一个开口端。 而且您有一些球恰好适合管道。 因此,当您将这些球插入管道时,它们会相互堆叠。 但是,当您将球卸下时,最后一个将被首先卸下。

Python Stack推送 (Python Stack push)

Well, there is no additional data structure as python stack. But as stack is a very common data structure, we will try to implement that.

好吧,没有像python堆栈那样的其他数据结构。 但是由于堆栈是非常常见的数据结构,因此我们将尝试实现该结构。

So if you have already studied about stack, you should know that stack has two operations. One is push and another is pop. In this section we will be discussing about push operation. Push operation is used to add items to the stack. As we will be using Python List as stack, we can use append() function to push items into the list.

因此,如果您已经学习过堆栈,则应该知道堆栈有两个操作。 一个是push ,另一个是pop 。 在本节中,我们将讨论推入操作。 推送操作用于将项目添加到堆栈中。 因为我们将使用Python List作为堆栈,所以我们可以使用append()函数将项目推入列表中。

stack = []  # initialize a list as stack
print('current stack :', stack)# add items to the stack
for i in range(5):# push items into stackstack.append(i)print('current stack :', stack,'\tstack size :', len(stack))

The output of above stack implementation example will be like below image.

上面的堆栈实现示例的输出将如下图所示。

Python堆栈弹出 (Python Stack pop)

Now we need to learn how to pop items from stack. Python List has a function named pop() that removes the last element from the list. But before removing you have to check if the stack is empty. So, if we add pop implementation to the previous code, then the final code will be like below.

现在我们需要学习如何从堆栈中弹出项目。 Python列表具有一个名为pop()的函数,该函数从列表中删除最后一个元素。 但是在删除之前,您必须检查堆栈是否为空。 因此,如果我们在先前的代码中添加pop实现,那么最终的代码将如下所示。

stack = []  # initialize a list as stack
print('\ncurrent stack :', stack)print('\nPush items to the stack')
# add items to the stack
for i in range(5):# push items into stackstack.append(i)print('current stack :', stack,'\tstack size :', len(stack))print('\nPop items from te stack')
# now pop items from the stack
while len(stack) > 0:  # check if the stack is emptystack.pop()print('current stack :', stack, '\tstack size :', len(stack))

So, the output will be as like below.

因此,输出将如下所示。

Push items to the stack
current stack : [0]     stack size : 1
current stack : [0, 1]     stack size : 2
current stack : [0, 1, 2]     stack size : 3
current stack : [0, 1, 2, 3]     stack size : 4
current stack : [0, 1, 2, 3, 4]     stack size : 5Pop items from te stack
current stack : [0, 1, 2, 3]     stack size : 4
current stack : [0, 1, 2]     stack size : 3
current stack : [0, 1]     stack size : 2
current stack : [0]     stack size : 1
current stack : []     stack size : 0

Python Stack实施 (Python Stack implementation)

As you see that we can utilize List append() and pop() functions to create our Stack implementation class. Here is a Stack implementation class with example.

如您所见,我们可以利用List append()和pop()函数创建我们的Stack实现类。 这是一个带有示例的Stack实现类。

class Stack:stack = []  # empty listmax_size = -1def __init__(self, size=-1):  # defining maximum size in the constructorself.max_size = sizedef push(self, item):if self.max_size == -1:  # if there is no limit in stackself.stack.append(item)elif len(self.stack) < self.max_size:  # if max limit not crossedself.stack.append(item)else:  # if max limit crossedprint('Can\'t add item. Stack limit is :', self.max_size)raise RuntimeErrordef pop(self):if len(self.stack) > 0:temp = self.stack[-1]self.stack.pop()return tempelse:print('stack is already empty.')raise IndexErrordef top(self):if len(self.stack) > 0:return self.stack[-1]  # returns the last itemelse:print('stack is already empty.')raise IndexErrorstack = Stack()
stack.push(1)  # push item 1
stack.push(2)  # push item 2
print('Pop the last item :', stack.pop())  # pop the top item
print('Current top item is :', stack.top())  # current top item

The above code will output like this

上面的代码将这样输出

Pop the last item : 2
Current top item is : 1

So, that’s all about python stack. If you have any confusion regarding python stack implementation, please use the comment box.

所以,这一切都与python堆栈有关。 如果您对python堆栈的实现有任何疑问,请使用注释框。

Reference: Official Guide

参考: 官方指南

翻译自: https://www.journaldev.com/16045/python-stack

python 堆栈

python 堆栈_Python堆栈相关推荐

  1. python实现堆栈_Python堆栈实现计算器

    原博文 2017-10-28 01:16 − 一.程序介绍 需求: 开发一个简单的python计算器 1.实现加减乘除及拓号优先级解析 2.用户输入 -1 - 2 *((-60+30+(-40/5)* ...

  2. 数据结构 python堆_Python中的堆栈数据结构是什么?

    成为专业认证的数据结构是数据值的集合,它们之间的关系,以及可以应用于数据的函数或操作.现在有很多可用的数据结构.但今天我们的重点将放在堆栈数据结构上.我将讨论以下主题:为什么是数据结构?数据结构类型什 ...

  3. python异常处理_Python学习点滴04 - 学会异常处理(2)

    前言 我们在开发Python程序时经常会遇到一些错误(语法错误和异常),尤其是程序代码发生异常(Exceptions)时,如果不能及时捕获异常和有效处理异常,则程序运行会被终止,有可能会造成相应的后果 ...

  4. python画代码-Python教程_Python画Mandelbrot集 代码

    Python教程_Python画Mandelbrot集 代码 作者:Comet 来源: 课课家 www.kokojia.com点击数:278发布时间:2015-06-19 11:17:19 曼德勃罗集 ...

  5. 内核堆栈 用户堆栈_弹性堆栈介绍

    内核堆栈 用户堆栈 当您运行对公司至关重要的软件时,您将无法拥有仅用于分析一段时间前发生的事情的日志,让客户端告诉您您的应用程序已损坏,而您甚至不知道发生了什么是真实的问题. 解决该问题的方法之一是使 ...

  6. 堆栈跟踪 堆栈跟踪_寻找缺少的堆栈跟踪

    堆栈跟踪 堆栈跟踪 我们最近在博客中发表的一篇评论带回了有关特定体验的一些回忆. 我希望我没有经历过的那种经历. 在创建Plumbr之前很长一段时间,我正在调试一个应用程序,该应用程序每次在蓝月亮时都 ...

  7. 内核堆栈 用户堆栈_堆栈痕迹从何而来?

    内核堆栈 用户堆栈 我相信,阅读和理解堆栈跟踪是每个程序员都必须具备的一项基本技能,以便有效地解决每种JVM语言的问题(另请参阅: 过滤日志中无关的堆栈跟踪行和首先记录引起根的异常 ). 那么我们可以 ...

  8. 数据结构堆栈 内存堆栈_了解堆栈数据结构

    数据结构堆栈 内存堆栈 In this article, we'll be understanding the working and the need for the Stack Data Stru ...

  9. 数据结构堆栈 内存堆栈_零堆栈数据科学家第二部分秋天

    数据结构堆栈 内存堆栈 In Hollywood, it is known that the sequels are rarely better than the original movie/par ...

最新文章

  1. 简单介绍Go 语言常见的一些坑
  2. boost::convert模块实现默认转换器fail失败的测试程序
  3. Unity 2017 Game Optimization 读书笔记 Dynamic Graphics(2)
  4. activiti api文档_【白银人机】Activiti 工作流从入门到入土:完整 hello world 大比拼(API 结合实例讲解)...
  5. 第四讲 构建安全的Microsoft ASP.NET 应用的最佳实践和技术
  6. 如何把即时通讯软件做大做强?
  7. Linux—vi/vim全局替换
  8. 从资深遥控器在家工作的5个技巧
  9. CentOS 7.2下ELK分析Nginx日志生产实战(高清多图)
  10. Echarts数据可视化全解注释
  11. 【转】vc6.0配置STLPort
  12. 严蔚敏数据结构习题第五章
  13. 2023昆明理工大学计算机考研信息汇总
  14. 富有人情味的入住体验
  15. (一) u-boot 基本介绍
  16. 推荐一些免费的网盘给你
  17. SSH配置公钥后仍需要输入密码问题解析
  18. PMI、国家外专局-项目管理高端论坛在深圳召开
  19. 自动驾驶 - 滤波算法
  20. 【Linux】网络套接字编程

热门文章

  1. 推理机Jess、Racer、Jena 比较 (转)
  2. [转载] c++的vector赋值方法汇总
  3. [转载] Python中的Phyllotaxis模式| 算法植物学的一个单位
  4. [转载] python中try Except抛出异常使用方法
  5. java 通过反射获取数组
  6. 【Java Web开发学习】Spring MVC 拦截器HandlerInterceptor
  7. 校赛热身 Problem C. Sometimes Naive (状压dp)
  8. GCC the GNU
  9. Linux常用命令及配置--简单
  10. linq里的select和selectmany操作 投影运算