Background
Imagine a scenario where we define the function foo to generate a random code greater than 0. However, the function execution may have an exception, and for the exception we specify that the function returns-1.
In the case of batch processing, we want to get a collection of the return values of all successfully executed Foo functions, ignoring the case of return-1. The basic logic is as follows:
result = [] for in item_lst: = foo (item) if code! =-1 : result.append (code)
Solutions for using list derivation
If you want to implement it in the form of a list deduction, there are several solutions:
Solution 1:
for inch forif code! =-1]
The return value of the function is obtained by using a list deduction, and then the filter is performed, and a two-time list deduction is required.
Solution 2:
for inch if foo (item)! =-1]
Performs a list deduction once, but it is clear that the Foo function was executed two times. It can be problematic if the Foo function is time-consuming, or if multiple executions can have side effects.
Solution 3:
for inch for inch if Code! =-1]
Using a generator expression to handle intermediate results, without a temporary list, and based on iterators, is preferable to both methods.
Reference
- How to execute a filter by function return value in list comprehension?
"Tips" Python implementation list deduction for function return values