[英]Python: Creating a filter function
I'm trying to create a function:我正在尝试创建一个函数:
filter(delete,lst)
When someone inputs:当有人输入时:
filter(1,[1,2,1])
returns [2]
返回[2]
What I have come up with was to use the list.remove function but it only deletes the first instance of delete.我想出的是使用 list.remove 函数,但它只删除第一个删除实例。
def filter(delete, lst):
"""
Removes the value or string of delete from the list lst
"""
list(lst)
lst.remove(delete)
print lst
My result:我的结果:
filter(1,[1,2,1])
returns [2,1]
返回[2,1]
Try with list comprehensions:尝试使用列表推导式:
def filt(delete, lst):
return [x for x in lst if x != delete]
Or alternatively, with the built-in filter function:或者,使用内置过滤器功能:
def filt(delete, lst):
return filter(lambda x: x != delete, lst)
And it's better not to use the name filter
for your function, since that's the same name as the built-in function used above最好不要为您的函数使用名称filter
,因为它与上面使用的内置函数的名称相同
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))
Custom filter function in python: python中的自定义过滤器功能:
def myfilter(fun, data):
return [i for i in data if fun(i)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.