如何在基于数组的列表中实现remove()方法?

时间:2018-04-30 10:58:14

标签: python arrays list arraylist

我是Python的新手,我刚开始学习如何在Python中使用类。所以我有一个名为list的类,我试图实现remove()方法。

如果a_list=[1,3,3,3,2]a_list.remove(3)假设给我1,3,3,2。但是,我编写的删除方法输出a_list=[1,3,2]

似乎我编写的方法会在输出列表中放置任何重复数字的实例。这是我的remove()方法。

 def remove(self, item):
    index=0
    if item not in self.array:
        raise ValueError("Item not in list")
    while index<len(self):
        if self.array[index]==item:
            for i in range(index,self.count-1):
                self.array[i]=self.array[i+1]
            self.count-=1
        index+=1

其中self.count指的是列表中的下一个可用位置。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果有人想知道在哪里放置休息声明:

def remove(self, item):
    index=0
    if item not in self.array:
        raise ValueError("Item not in list")
    while index<len(self):
        if self.array[index]==item:
            break
        index+=1

    for i in range(index,self.count-1):
        self.array[i]=self.array[i+1]
    self.count-=1