简体   繁体   English

使用lambda函数从列表中过滤元素值

[英]using lambda function to filter element value from list

how can I rewrite the following code by using lambda function?the problem i have is to make x as variable so I can return different list based on input 我该如何使用lambda函数重写以下代码?我遇到的问题是使x为变量,因此我可以根据输入返回不同的列表

s_list = [1,2,3,4,5,6]
def f(x):
    return [a for a in s_list if a not in x]

print(f([1,2]))#[3,4,5,6]
print(f([4,6]))#[1,2,3,5]

If you don't need s_list like a argument, you can use this: 如果不需要像参数一样使用s_list ,则可以使用以下命令:

F = lambda x: [a for a in [1,2,3] if a not in x]

and if you need s_list like an argument, you could make this: 如果您需要像参数一样的s_list,则可以执行以下操作:

F = lambda x, s_list: [a for a in s_list if a not in x]

Here's a way to write your function using filter : 这是使用filter编写函数的一种方式:

def f2(x):
    return filter(lambda a: a not in x, s_list)

print(f2(x=[1,2]))
#[3, 4, 5, 6]
print(f2(x=[4,6]))
#[1, 2, 3, 5]
print(f2(x=[]))
#[1, 2, 3, 4, 5, 6]

Or if you wanted it to be a function of both s_list and x : 或者,如果您希望它既是s_list又是x

def f3(s_list, x):
    return filter(lambda a: a not in x, s_list)

print(f3(s_list, x=[1,2]))
#[3, 4, 5, 6]
print(f3(s_list, x=[4,6]))
#[1, 2, 3, 5]
print(f3(s_list, x=[]))
#[1, 2, 3, 4, 5, 6]

You can achieve that by using Filter method : 您可以使用Filter方法来实现:

s_list = [1,2,3,4,5,6]

x_=[1,2]

print(list(filter(lambda x:x not in x_,s_list)))

output: 输出:

[3, 4, 5, 6]

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

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