Temporary variables in list comprehensions

Antonio Caminero Garcia tonycamgar at gmail.com
Mon Jan 9 14:15:59 EST 2017


On Sunday, January 8, 2017 at 7:53:37 PM UTC-8, Steven D'Aprano wrote:
> Suppose you have an expensive calculation that gets used two or more times in a 
> loop. The obvious way to avoid calculating it twice in an ordinary loop is with 
> a temporary variable:
>> result = []
> for x in data:
> tmp = expensive_calculation(x)
> result.append((tmp, tmp+1))
>>> But what if you are using a list comprehension? Alas, list comps don't let you 
> have temporary variables, so you have to write this:
>>> [(expensive_calculation(x), expensive_calculation(x) + 1) for x in data]
>>> Or do you? ... no, you don't!
>>> [(tmp, tmp + 1) for x in data for tmp in [expensive_calculation(x)]]
>>> I can't decide whether that's an awesome trick or a horrible hack...
>>> -- 
> Steven
> "Ever since I learned about confirmation bias, I've been seeing 
> it everywhere." - Jon Ronson

Hello I saw some memoizing functions, in that sense you can use the functools.lru_cache decorator, that is even better if you have repeated elements in data.
@functools.lru_cache
def expensive_calculation(x):
 # very NP-hard calculation
 pass
Hope that helps :)


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /