Reputation: 19349
The way it is I can only call funct()
once per iteration. So I can't do this:
result=[funct(arg) for arg in args if arg and funct(arg)]
If there is a connection drop this function returns None
. If None is returned I don't want to add it to the resulted list. How to achieve it?
def funct(arg):
if arg%2: return arg*2
args=[1,2,3,None,4,5]
result=[funct(arg) for arg in args if arg]
print result
Upvotes: 0
Views: 109
Reputation: 180481
You can use filter as you will not be returning any 0
values to your list:
result = filter(None,map(funct,filter(None,args)))
It will filter your args
list and any None
values returned
On a list with 20 elements args:
In [18]: %%timeit
[val for arg in args
if arg
for val in [funct(arg)]
if val is not None]
....:
100000 loops, best of 3: 10.6 µs per loop
In [19]: timeit filter(None,map(funct,filter(None,args)))
100000 loops, best of 3: 6.42 µs per loop
In [20]: timeit [a for a in [funct(arg) for arg in args if arg] if a]
100000 loops, best of 3: 7.98 µs per loop
Upvotes: 2
Reputation: 1107
you can nest comprehensions
result=[a for a in [funct(arg) for arg in args if arg] if a]
Upvotes: 1