Temporary variables in list comprehensions
Robert L.
No_spamming at noWhere_7073.org
Sat Apr 1 20:08:05 EDT 2017
On 1/8/2017, 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)]]
[2,3,5].map{|n| tmp = Math.sqrt n; [tmp, tmp+1]}
===>
[[1.4142135623730951, 2.414213562373095],
[1.7320508075688772, 2.732050807568877],
[2.23606797749979, 3.23606797749979]]
--
I don't believe in western morality, i.e. don't kill civilians or children....
The only way to fight a moral war is the Jewish way: Destroy their holy sites.
Kill men, women, and children (and cattle). --- Rabbi Manis Friedman
web.archive.org/web/20090605154706/http://www.momentmag.com/Exclusive/2009/2009-06/200906-Ask_Rabbis.html
archive.org/download/DavidDukeVideo/TheZionistMatrixOfPowerddhd.ogv
More information about the Python-list
mailing list