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?
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With