首页 > 解决方案 > 你能在python中制作对列表进行操作的函数吗?

问题描述

在 python 中,您有对列表进行操作的内置函数,例如list.remove()list.pop()

您可以制作自己的自定义函数来执行此操作吗?我希望能够做到这一点:

def removeAll(self,value):
  while value in self:
    self.remove(value)

list = ["1","2","3","3","4","3","5"]
list.removeAll("3")
print(list)
#Outputs '["1","2","4","5"]

只是一个例子。

标签: pythonlistfunctionclass

解决方案


您不能修改内置类型,但您当然可以从列表中派生自己的类:

class mylist(list):
    def removeAll(self,n):
        while n in self:
            self.remove(n)

x = mylist([1,1,2,2,3,3,4,4])
x.removeAll(3)
print(x)

推荐阅读