Python:创建过滤函数

2 投票
4 回答
8591 浏览
提问于 2025-04-17 06:33

我正在尝试创建一个函数:

filter(delete,lst) 

当有人输入:

filter(1,[1,2,1]) 

返回 [2]

我想到的方法是使用 list.remove 函数,但它只会删除第一个出现的值。

def filter(delete, lst):

"""

Removes the value or string of delete from the list lst

"""

   list(lst)

   lst.remove(delete)

   print lst

我的结果:

filter(1,[1,2,1])

返回 [2,1]

4 个回答

0

自定义过滤函数

def my_filter(func,sequence):
    res=[]
    for variable in sequence :
        if func(variable):
            res.append(variable)
    return res

def is_even(item):
    if item%2==0 :
        return True
    else :
        return False
 
    

seq=[1,2,3,4,5,6,7,8,9,10]
print(my_filter(is_even,seq))
0

我喜欢Óscar López的回答,但你也应该学会使用Python中现有的filter函数:

>>> def myfilter(tgt, seq):
        return filter(lambda x: x!=tgt, seq)

>>> myfilter(1, [1,2,1])
[2]
8

试试用列表推导式:

def filt(delete, lst):
    return [x for x in lst if x != delete]

或者,可以用内置的过滤函数:

def filt(delete, lst):
    return filter(lambda x: x != delete, lst)

而且最好不要把你的函数命名为 filter,因为这个名字和上面提到的内置函数是一样的

撰写回答