Help, replacing the actual value from a data strucutre in a iterator

Andrew McGregor andrew at indranet.co.nz
Sat Jan 4 20:09:14 CET 2003


I just liked the wierd look of the no-argument lambda :-)

You're right, just returning the element straight is more efficient.

--On Saturday, January 04, 2003 17:59:26 +0000 Bengt Richter <bokr at oz.net> 
wrote:

> On Sun, 05 Jan 2003 01:15:35 +1300, Andrew McGregor
> <andrew at indranet.co.nz> wrote:
>
>> Hi,
>>
>> --On Saturday, January 04, 2003 03:31:06 -0800 george hart
>> <gehart24 at yahoo.com> wrote:
>>
>>>> o is now bound to 0
>>>>
>>>> > o=100   # where i want this assignment to change a[0] to 100
>>>>
>>>> No way.  You are simply rebinding 'o' to a new value.  Just write
>>>> 'a[0] = 100'!
>>>
>>> Hi,
>>>
>>> I'm sorry, I think my example was not very good.  I can't just write
>>> 'a[0]' because the *real* data structure I am working with is very
>>> complex and nested.  It would be more like a[1][10][20][40] etc..
>>>
>>> I am a relatively new to python so I am probably trying solve the
>>> problem the way I would in C (it would be nice to have pointers right
>>> now :-).   The returned value from the .next() method appears to be
>>> pointing to the same memory address as the respective element in the
>>> data structure.  It seems logical that there should be an easy way to
>>> modify it.
>>
>> It is pointing to the same address; but it's the address of the integer
>> value 0, not the list slot containing that 0.
>>
>>> Plus, there must be a way to do this?  What is the point of being able
>>> use a generator to iterate over a structure if you can't modify any of
>>> the values?
>>
>> How about:
>>
>> from __future__ import generators
>> from types import *
>>
>> a=[0,1,2,[20,30,40],9,3]
>> def generator(l):
>>    for i in xrange(len(l)):
>>        if type(l[i]) is list:
>>            for q in generator(l[i]):
>>                yield q
>>        else:
>>            yield (lambda : l.__getitem__(i),
>>                   lambda x: l.__setitem__(i, x))
>>
>> print a
>> gen = generator(a)
>> g, s = gen.next()
>> print g()
>> s(100)
>> print a
>> g, s = gen.next()
>> g, s = gen.next()
>> g, s = gen.next()
>> g, s = gen.next()
>> s(100)
>> print a
>>
>> which prints:
>> [0, 1, 2, [20, 30, 40], 9, 3]
>> 0
>> [100, 1, 2, [20, 30, 40], 9, 3]
>> [100, 1, 2, [20, 100, 40], 9, 3]
>>
> That's prettier than what I suggested, but probably not a fast.
>
> Also, though it breaks the symmetry, why not
>
>             yield (l[i], lambda x: l.__setitem__(i, x))
>
> since getting doesn't need to be wrapped?
>
> Regards,
> Bengt Richter
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>







More information about the Python-list mailing list