简体   繁体   English

过滤器使用 lambda function 和 zip

[英]filter using lambda function and zip

I am trying to check if the list is empty return the related description using filter with lambda function and zip.我正在尝试检查列表是否为空,使用带有 lambda function 和 zip 的过滤器返回相关描述。

its working but the result is not as expected.它的工作,但结果并不像预期的那样。

list_of_lists = [ [ ] , [ 'not_empty' ] ]
list_of_desc = [ 'first_list_is_empty' , 'second_list_not_empty' ]

result = list(filter(lambda item : item[1] if not item[0] else '',zip(list_of_lists,list_of_desc )))

result
Out[180]: [([], 'first_list_is_empty')]

Dont understand why its returning the tuple, i was expecting 'first_list_is_empty' as i'm slicing the tuple.不明白为什么它返回元组,我期待'first_list_is_empty',因为我正在切片元组。

This is because filter() does not modify what is returned, it only uses the lambda to determine if it "should" return the tuple.这是因为 filter() 不会修改返回的内容,它只使用 lambda 来确定它是否“应该”返回元组。 To be clear:要清楚:

func = lambda item : item[1] if not item[0] else ''
func = lambda item : bool(item[1] if not item[0] else '')

Are the exact same filtering function.是完全相同的过滤 function。

To modify what is returned, use the builtin map() function instead.要修改返回的内容,请改用内置 map() function。 Also note that filter() defaults to removing False things automatically, you don't need a lambda.另请注意,filter() 默认自动删除 False 事物,您不需要 lambda。

func   = lambda item : item[1] if not item[0] else ''
result = list(filter(None,map(func,zip(list_of_lists,list_of_desc))))

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

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