Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a filter by function return value in list comprehension?

Below is the basic logic:

result = []

for item in item_lst:
    code = foo(item)
    if code != -1:
        result.append(code)

With list comprehension, I should write twice:

result = [foo(item) for item in item_lst]
result = [code for code in result if code != -1]

Or

result = [foo(item) for item in item_lst if foo(item) != -1]

Which will call function foo twice.

Is there any better solutions?

like image 375
sting_roc Avatar asked Sep 06 '25 03:09

sting_roc


2 Answers

You can use a generator expression to avoid creating a second list:

result = [code for code in (foo(item) for item in item_ls) if code != -1]

Here:

(foo(item) for item in item_ls) 

is a generator expression. No intermediate list is created. This potentially helps to save memory.

like image 152
Mike Müller Avatar answered Sep 07 '25 20:09

Mike Müller


You can use filter and map, it is shorter and maybe clearer:

restuls = filter(lambda x: x != -1, map(foo, item_ls))

this would work for python3 for python 2 consider using itertools.imap to avoid intermediate list creation:

from itertools import imap
restuls = filter(lambda x: x != -1, imap(foo, item_ls))
like image 22
Netwave Avatar answered Sep 07 '25 19:09

Netwave