Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:创建过滤器函数_Python_List_Function - Fatal编程技术网

Python:创建过滤器函数

Python:创建过滤器函数,python,list,function,Python,List,Function,我正在尝试创建一个函数: filter(delete,lst) 当有人输入: filter(1,[1,2,1]) 返回[2] 我想到的是使用list.remove函数,但它只删除delete的第一个实例 def filter(delete, lst): """ Removes the value or string of delete from the list lst """ list(lst) lst.remove(delete) print lst

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

filter(delete,lst) 
当有人输入:

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

我想到的是使用list.remove函数,但它只删除delete的第一个实例

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]

尝试列表理解:

def filt(delete, lst):
    return [x for x in lst if x != delete]
或者,使用内置过滤器功能:

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

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

最好不要为您的函数使用名称
filter
,因为这与上面使用的内置函数名称相同

请尝试列表理解:

def filt(delete, lst):
    return [x for x in lst if x != delete]
或者,使用内置过滤器功能:

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

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

最好不要为您的函数使用名称
filter
,因为它与上面使用的内置函数同名

我喜欢Óscar López的答案,但您还应该学会使用现有的Python函数:

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

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

我喜欢Óscar López的答案,但您还应该学习使用现有的Python函数:

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

>>> myfilter(1, [1,2,1])
[2]
自定义筛选函数 自定义筛选函数
python中的自定义筛选函数:

def myfilter(fun, data):
    return [i for i in data if fun(i)]

python中的自定义筛选函数:

def myfilter(fun, data):
    return [i for i in data if fun(i)]

我建议为你的函数选择一个不同的名称。有一个内置的
过滤器
功能,您将屏蔽它。我之所以称我的功能为“过滤器”,是应本作业中讲师的要求。这是否回答了您的问题?我建议为你的函数选择一个不同的名称。有一个内置的
过滤器
功能,您将屏蔽它。我之所以称我的功能为“过滤器”,是应本作业中讲师的要求。这是否回答了您的问题+1.我只想补充一点,最好不要使用
过滤器
作为名称,因为它已经是内置的。谢谢您的回答。我之所以称我的函数为“过滤器”,是因为我的老师在这项作业中提出了要求。HighAllegiant:在这种情况下,请在你的问题中添加家庭作业标签。给你一个毫无帮助的答案。在这个问题和你的另一个问题之间,在我看来,你的导师似乎下定决心让人们无缘无故地用困难的方式解决简单的问题(+1.我只想补充一点,最好不要使用
过滤器
作为名称,因为它已经是内置的。谢谢你的回答。我之所以称我的函数为“过滤器”HighAllegiant:在这种情况下,请在你的问题上加上家庭作业标签。给你的答案毫无帮助。在这个问题和你的另一个问题之间,在我看来,你的老师似乎下定决心让人们无缘无故地用困难的方式解决简单的问题[2,4,6,8,10]。此处为偶数和func的地址相同。输出将为[2,4,6,8,10]。此处为偶数和func的地址相同。