简体   繁体   中英

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.

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.

This is because filter() does not modify what is returned, it only uses the lambda to determine if it "should" return the tuple. 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.

To modify what is returned, use the builtin map() function instead. Also note that filter() defaults to removing False things automatically, you don't need a lambda.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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