【问题标题】:Add two list to one list将两个列表添加到一个列表
【发布时间】:2020-04-26 14:30:55
【问题描述】:

我正在尝试将通过一个类创建的两个列表合并到一个新列表中。我使用__add__ 函数。 但它不断添加前两个索引并停止。

这是我的代码:

class Stack:
    def __init__(self):
        self.__items = []
        self.__top = 0

    def is_Empty(self):
        return self.__top <= 0
        try:
            raise Exception('Stack empty.')
        except Exception as error:
            print(error)

    def __str__(self):
        """Print current stack"""
        if self.is_Empty() == True:
            return "Stack empty"
        else:
            return "Stack is not empty"

    def push(self, item):
        """Push item in stack."""
        self.__items.append(item)
        self.__top += 1

    def pop(self):
        """Remove top of the stack."""
        if self.__top <= 0:
            return self.is_Empty()
        self.__top -= 1
        return self.__items.pop()

    def top(self):
        """Return top of the stack."""
        if self.__top <= 0:
            return self.is_Empty()
        else:
            return self.__items[-1]

    def my_stack(self):
        """Show the current stack"""
        if self.__items == []:
            return self.is_Empty()
        else:
            return f"The current stack is {self.__items}"

    def __add__(self,other):
        """Add two lists together"""
        newlst = []
        for i, j in zip(self.__items, other.__items):
            newlst.append(i+j)
            return newlst

    def __eq__(self, other):
        """Return True if two list is equal else Return False """
        return (self is other) or (self.__items) == (other.__items)

例如:

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack2 = Stack()
stack2.push(4)
stack2.push(5)
stack2.push(6)

现在我正在尝试将两个堆栈添加到stack3

stack3 = stack + stack2

我得到的结果是这样的:

>>> print(stack3)
[5]

我的目标是像这样获得stack3

>>> print(stack3)
[1, 2, 3, 4, 5, 6]

【问题讨论】:

    标签: python python-3.x list class


    【解决方案1】:

    您当前的代码

       def __add__(self,other):
            """Add two lists together"""
            newlst = []
            for i, j in zip(self.__items, other.__items):
                newlst.append(i+j)
                return newlst
    

    添加每个.__items 列表的第一个元素,然后返回结果。

    要一个接一个地添加内部列表并作为列表返回,这样可以:

    def __add__(self, other):
        """Add two lists together"""
        if isinstance(other,Stack):
            return self.__items + other.__items
    
        return [] # or self.__items or raise Exception
    

    要返回一个新的Stack-instance,你可以这样做:

    def __add__(self, other):
        """Add two lists together"""
        if isinstance(other, Stack):
            s = Stack()
            for item in self.__items:
                s.push(item)
            for item in other.__items:
                s.push(item)
             return s
        return [] # or self.__items or raise Exception
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-24
      • 2015-07-22
      相关资源
      最近更新 更多