sting_roc
sting_roc

Reputation: 253

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?

Upvotes: 4

Views: 426

Answers (3)

Netwave
Netwave

Reputation: 42746

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))

Upvotes: 2

Mike Müller
Mike Müller

Reputation: 85492

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.

Upvotes: 6

dhirajforyou
dhirajforyou

Reputation: 462

Give it a try:

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

Upvotes: 0

Related Questions