Python:创建过滤函数

标签 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(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)

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

关于Python:创建过滤函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8176862/

相关文章:

python - 使用 Python 3 对数组进行排序

python - 计算两个文件的行差异的最有效方法是什么?

我可以安全地将第一个结构成员的地址解释为整个结构的地址吗?

python - 循环遍历字典列表python

function - "verbatim"函数

c - 头文件中是否需要函数原型(prototype)?

python - 使用正则表达式Python根据模式提取部分字符串

python - 如何减少 numpy 数组的维度,然后从末尾修剪一些?

python - 通过列表理解展平列表列表

javascript - 在javascript的另一个函数中将一个函数作为arg传递