在python

时间:2017-12-29 14:33:19

标签: python list object stack queue

所以我试图在Python中创建一个堆栈对象列表。我首先创建了一个类Stack,它具有Stack应该具有的简单方法。然后我创建了另一个名为Stacks的类。我正在尝试创建堆栈列表。如果一个堆栈有超过3个元素,它会创建一个新堆栈,但是当我尝试显示这些元素时出现错误。有人可以指出我在这里做错了吗?

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 size(self):
        return len(self.items)

    def printStack(self):
        for item in reversed(self.items):
            print (item)


class Stacks:

    def __init__(self):
        self.stacks = []
        self.noOfStacks = 0
        self.itemsOnStack = 0

    def dev(self):
        self.stacks.append(Stack())
        # if len(self.stacks) != 0:
        #     self.noOfStacks += 1

    def push(self, item):
        if self.itemsOnStack > 3:
            self.dev()
        else:
            self.itemsOnStack += 1
            self.stacks[self.noOfStacks].push(item)

    def pop(self, stackNo):
        return self.stacks(noOfStacks).pop()

    def size(self):
        return len(self.stacks)

    def printtack(self, index):
        print (len(self.stacks(index)))
        self.stacks(index).printStack()


stacky = Stacks()
stacky.dev()
stacky.push(3)
stacky.printtack(0)

2 个答案:

答案 0 :(得分:1)

Python中的索引列表由[] not()工作。尝试

 def printtack(self, index):
    self.stacks[index].printStack()

答案 1 :(得分:0)

需要注意的一点是,kshikama表示索引应该使用[]而不是()来完成,另一个问题是使用堆栈类中的len()方法。 __len__()方法或您给出的使用size()方法

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 size(self):
        return len(self.items)

    def printStack(self):
        for item in reversed(self.items):
            print (item)

class Stacks:
    def __init__(self):
        self.stacks = []
        self.noOfStacks = 0
        self.itemsOnStack = 0

    def dev(self):
        self.stacks.append(Stack())
        #if len(self.stacks) != 0:
            #self.noOfStacks += 1

    def push(self, item):

        if self.itemsOnStack > 3:
            self.dev()
        else:
            self.itemsOnStack += 1
            self.stacks[self.noOfStacks].push(item)


    def pop(self, stackNo):
        return self.stacks(noOfStacks).pop()

    def size(self):
        return len(self.stacks)

    def printtack(self, index):
        print (self.stacks[index].size())
        self.stacks[index].printStack()
stacky = Stacks()
stacky.dev()
stacky.push(3)
stacky.printtack(0)

输出

1
3