Python:先进先出打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19219903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:10:32  来源:igfitidea点击:

Python: First In First Out Print

pythonlifo

提问by arcwinolivirus

I'm a beginner in python and I'm having an issue with this program:

我是 python 的初学者,这个程序有问题:

The program below is a Last In First Out (LIFO). I want to make it First in First Out (FIFO) Program.

下面的程序是后进先出 (LIFO)。我想使其成为先进先出 (FIFO) 程序。

from NodeList import Node

class QueueLL:

    def __init__(self):
        self.head = None


    def enqueueQLL(self,item):
        temp = Node(str(item))
        temp.setNext(self.head) 
        self.head = temp
        length = max(len(node.data) for node in self.allNodes()) if self.head else 0
        print('\u2510{}\u250c'.format(' '*length))
        for node in self.allNodes():
            print('\u2502{:<{}}\u2502'.format(node.data, length))
        print('\u2514{}\u2518'.format('\u2500'*length))

Here is the NodeList:

这是节点列表:

class Node:

    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

NOTE: The "Rainbow" should be at the bottom of "Arc" or in FIFO (pic below is LIFO)

注意:“Rainbow”应该在“Arc”的底部或在 FIFO 中(下图是 LIFO)

I'm thinking to put a new def like setPrevious in the NodeList But I dont know how. (to be honest I'm really new on these self.head = none stuffs . I used to write self.items = [])

我想在 NodeList 中放置一个像 setPrevious 这样的新 def 但我不知道如何。(说实话,我对这些 self.head = none 东西真的很陌生。我曾经写过 self.items = [])

Any help and tips will be appreciated! Thank you!

任何帮助和提示将不胜感激!谢谢!

回答by Constantinius

Apart from learning purposes I would not advise using a custom data structure for making a LIFO or FIFO. The built in data-type listis just fine after all.

除了学习目的,我不建议使用自定义数据结构来制作 LIFO 或 FIFO。list毕竟内置的数据类型很好。

You can add items using the appendmethod and remove them using pop. For a LIFO this would look like this:

您可以使用append方法添加项目并使用删除它们pop。对于 LIFO,这看起来像这样:

stack = list()
stack.append(1)
stack.append(2)
stack.append(3)

print stack.pop()  #3
print stack.pop()  #2
print stack.pop()  #1

If you supply an integer argument for popyou can specify which element to remove. For a FIFO use the index 0for the first element:

如果您提供一个整数参数,pop您可以指定要删除的元素。对于 FIFO,使用0第一个元素的索引:

stack = list()
stack.append(1)
stack.append(2)
stack.append(3)

print stack.pop(0)  #1
print stack.pop(0)  #2
print stack.pop(0)  #3

回答by Brōtsyorfuzthrāx

Well, seeing as your class is probably over now and you didn't mention your class (or that it had to be a linked list) in the question itself, I'll just tell you the built-in easy way to do it, for now, which is probably more pertinent to your current situation (and will help people who find your question).

好吧,鉴于您的课程现在可能已经结束并且您没有在问题本身中提及您的课程(或者它必须是一个链表),我将告诉您内置的简单方法,目前,这可能与您当前的情况更相关(并且会帮助找到您问题的人)。

import sys;
if sys.version_info[0]>2: #Just making sure the program works with both Python 2.x and 3.x
    from queue import Queue
else:
    from Queue import Queue

q=Queue()
q.put("first") #Put an item on the Queue.
q.put("second")
q.put("third")

while not q.empty(): #If it's empty, the program will stall if you try to get from it (that's why we're checking)
    print(q.get()) #Get an item from the Queue

This outputs

这输出

first
second
third

Really, though, I'm not sure what advantages this has over Constantinius's answer, but since it's an included module, I would think there must be an advantage somewhere. I know they are used with threads from the threading module. There are more functions associated with Queues than I've mentioned here.

确实,虽然,我不确定这比 Constantinius 的答案有什么优势,但由于它是一个包含的模块,我认为某处一定有优势。我知道它们与 threading 模块中的线程一起使用。与队列相关的函数比我在这里提到的要多。

To learn more, open your Python interpreter and type this:

要了解更多信息,请打开您的 Python 解释器并输入以下内容:

from queue import Queue #or from Queue import Queue for 2.x
help(Queue) #Press q to exit the help

Don't ask me what blocking is, but this mayuse the term how it's used in the Queue class documentation: http://en.wikipedia.org/wiki/Blocking_(computing)

不要问我什么是阻塞,但这可能会使用它在 Queue 类文档中如何使用的术语:http: //en.wikipedia.org/wiki/Blocking_(computing)

回答by Vinoth Karthick

class Box:
    def __init__(self,data):
        self.data=data
        self.next=None        
class List:
    def __init__(self):
        self.head=None        
    def add(self,item):                
        temp=Box(item)                
        if self.head==None:
            self.head=temp
            self.prev=temp
        self.prev.next=temp
        self.prev=self.prev.next               
    def PrintList(self):
        while self.head!=None:
            print(self.head.data)
            self.head=self.head.next

myList=List()
myList.add("Vinoth")
myList.add("Karthick")
myList.add("Ganesh")
myList.add("Malai")
myList.add("Shan")
myList.add("Saravana")
myList.PrintList()