繁体   English   中英

你能在python中制作对列表进行操作的函数吗?

[英]Can you make functions that operate on a list in 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)
list1 = ["1", "2", "3"]

def operations_on_a_list():

    size = int(input("Enter the number of elements you want to add in the list : "))

    for i in range(size):

        value = input("Enter the element you want to add in the list : ")

        list1.append(value)
    
    return list1

print(operations_on_a_list())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM