Help, replacing the actual value from a data strucutre in a iterator
Andrew McGregor
andrew at indranet.co.nz
Sat Jan 4 07:15:35 EST 2003
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]
>
>
> Thanks,
>
> George
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
More information about the Python-list
mailing list