简体   繁体   中英

When function can only be called once

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

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

你可以嵌套理解

result=[a for a in [funct(arg) for arg in args if arg] if a]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM