简体   繁体   English

尝试使用 lambda 过滤列表

[英]Trying to filter list using lambda

I'm trying to filter this list or real and fake Python keywords.我正在尝试过滤此列表或真实和虚假的 Python 关键字。 I'm using the keyword module to obtain the list.我正在使用关键字模块来获取列表。 While I got it to work using list comprehension, I'm stuck with lambda as I keep getting the same list in return.虽然我使用列表理解来让它工作,但我仍然坚持使用 lambda,因为我不断得到相同的列表作为回报。

Here is the code:这是代码:

import keyword

keyword_list = keyword.kwlist
iskeyword = ['False','Fake','else','however','or', 'True','Real','attempt','try','and','moreover']

# using list comprehension
new_keyword_list = [f'{k} is keyword' if k in keyword_list else f'{k} not keyword' for k in iskeyword]
new_keyword_list

# user-defined function
def check_keyword(c):
    return new_keyword_list

res = list(filter(check_keyword, new_keyword_list))
print(res)

And this is the output, which is correct:这是输出,这是正确的:

['False is keyword', 'Fake not keyword', 'else is keyword', 'however not keyword', 'or is keyword', 'True is keyword', 'Real not keyword', 'attempt not keyword', 'try is keyword', 'and is keyword', 'moreover not keyword']

Now, if I use lambda, I get the same result from the original iskeyword list.现在,如果我使用 lambda,我会从原始iskeyword列表中得到相同的结果。

# using lambda
new_keyword_list = filter(lambda k : (f'{k} is keyword' if k in keyword_list else f'{k} not keyword'), iskeyword)
new_keyword_list

I know I'm messing up with lambda, but where?我知道我在搞砸 lambda,但在哪里? Thanks for helping!感谢您的帮助!

That's how filter is supposed to work.这就是filter应该如何工作。 filter returns the elements of the original list for which the lambda returns True, which all of yours do. filter返回原始列表中 lambda 为其返回 True 的元素,您所有人都这样做。 I suspect you were really looking for map , but the list comprehension is a better solution.我怀疑你真的在寻找map ,但列表理解是一个更好的解决方案。

filter用于获取所有True值,修复方法是使用map

new_keyword_list = map(lambda k: f'{k} is keyword' if k in keyword_list else f'{k} not keyword', iskeyword)

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

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