Understanding a Python list with the same protection function and result

I was wondering if anyone has a good clean Pythonic and effective method of implementing concepts that include the same defense expression as the result. To be clear, consider the following simple example:

def f(a): print "Calling", a return a + 1 print [ f(v) for v in xrange(3) if f(v) > 1 ] 

Will open

 Calling 0 Calling 1 Calling 1 Calling 2 Calling 2 [2, 3] 

proving that f for most elements is called twice. This is fine, and we want if f has side effects, but if f is some expensive operation without side effects, a duplicate call is undesirable. But a solution that only calls once for each element seems awkward / verbose:

 intermediate = ( f(v) for v in xrange(3) ) print [ r for r in intermediate if r > 1 ] 

even if it is enclosed in one line

 print [ r for r in ( f(v) for v in xrange(3) ) if r > 1 ] 

So, can anyone come up with something better?

+5
source share
3 answers

You can use the filter() function:

 filter(lambda x: x > 1, [ f(v) for v in xrange(3)]) 

But this is about the same as the last proposed solution.

+2
source

How about memoizing f , for example :?

 def f(...): ... def some_or_other(): f = functools.lru_cache(1)(f) [ f(v) for v in xrange(3) if f(v) > 1 ] 

Remembering locally, given the area of ​​your calling site, has the advantage that after returning some_or_other() , the memo memory will be garbage collected, and you don’t have to worry about links to v that were passed to f() .

Since it is local, limiting the size of note 1 is sufficient.

In the simple case, you can also memoize f globally:

 @functools.lru_cache() def f(...): ... [ f(v) for v in xrange(3) if f(v) > 1 ] 
+1
source

What Andres Perez-Albela H. said, except for using map () the built-in function:

 filter(lambda x: x > 1, map(f, xrange(3))) 

You can also look at itertools , but I'm not sure if this example applies to this example. In more complex situations, although he may offer a solution.

0
source

Source: https://habr.com/ru/post/1237230/


All Articles