[python-nl] lambda rewrite question

Elit info at elit.nl
Wed Jun 29 16:33:20 CEST 2011


Hi,

I think the problem is that the lamba function tries to return the value stored 
at variable 'c', but that variable is only defined within the inner loop. So, if 
the lambda function gets called later on, it references 'c' which is not valid 
anymore.

You might be able to solve it by  doing:

d[key]['next'][k]['prob'] = lambda : float(c)

(So, move the float function into the lambda)

I hope this works (and that I'm not wrong :) )

Good luck,

Rinze



On 29-6-2011 16:01, Floris van Manen wrote:
> For those of you who know everything about the basic python syntax&  semantics ...
> I get stuck in a simple context issue (i think)
>
>
> this version works, it return the stored float value
>
> def rewrite( d ):
>      for key in d:
>          for k in d[key]['next']:
>              c = float(d[key]['next'][k]['prob'])
>              d[key]['next'][k]['prob'] = c
>      return d
>
>
>
> this doesn't
> if i call the function it will return a (random?) identical value for all stored lambda functions.
>
> def rewrite( d ):
>      for key in d:
>          for k in d[key]['next']:
>              c = float(d[key]['next'][k]['prob'])
>              d[key]['next'][k]['prob'] = lambda : c
>      return d
>
>
> There is most likely a reason to it.
> Can someone explain me what that reason is ?
>
> Thanks!
> .Floris
>
>
> _______________________________________________
> Python-nl mailing list
> Python-nl at python.org
> http://mail.python.org/mailman/listinfo/python-nl
>


More information about the Python-nl mailing list