python - 你能在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"]
只是一个例子。
解决方案
您不能修改内置类型,但您当然可以从列表中派生自己的类:
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)
推荐阅读
- spring-data-jpa - 如何在 Spring Data jpa 中获取 Connection 对象?
- java - Javafx:添加图像:java.lang.reflect.InvocationTargetException
- c++ - CodeLite 中的调试器未显示局部变量
- python - 修复图像中曝光过度的区域
- python-3.x - 合并具有重复名称的多索引列
- python - z:net.snowflake.spark.snowflake.Utils.runQuery。: java.lang.NullPointerException
- reactjs - 泛型还是分解?什么是正确的反应方法
- java - 如何在 Spring Boot 中从数据库更新应用程序上下文
- ios - 有没有一种简单的方法可以从 UITableView 中删除特定的自定义单元格?
- javascript - 转到路线并在事件处理程序中传递道具