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

Bengt Richter bokr at oz.net
Sat Jan 4 12:41:50 EST 2003


On 3 Jan 2003 19:42:51 -0800, gehart24 at yahoo.com (george hart) wrote:

>Hello,
>
>My problem is that I have a very complex data structure I need to
>iterate over and change certain values to.  I wrote a 'generator' to
>iterate over my data structure but when i call the next() method in
>the generator object I am returned a value that cannot be used to
>modifiy the original data structure.
>
>Here is a simplified version of my problem:
>
>a=[0,1,2,[20,30,40],9,3]
>def generator(l):
>    for i in l:
>        if type(i) is list:
>            for q in generator(i):
>                yield q
>        else:
>            yield i
>
>g=generator(a)
>o=g.next()
>o=100   # where i want this assignment to change a[0] to 100
>print a[0]  #thus a[0] would then print out 100
>
>
There are other ways to do what you want, but a simple way close to what you
tried, using lists, is to yield back the relevant list and index along with
the value, in case you want to change the value in the list it was in,
e.g., (obviously substitute your own logic instead of being in the example
hit list of [1, 30, 9, 3] to decide whether to modify the value):

(You could pass back a sequence of indices to get at the relevant list from
the root list, but it is simpler just to pass a reference to the current list
and one index).

====< georgehart.py >====================================
from __future__ import generators

a=[0,1,2,[20,30,40],9,3]
def generator(l):
    ix = 0
    for i in l:
        if type(i) is list:
            for q in generator(i):
                yield q
        else:
            yield (i, l, ix)
        ix += 1

print '\nBefore:',a,'\n----'

g=generator(a)
for tup  in g:
    print 'value %2s is in list %s at index %s' % tup
    o, olist, oix = tup
    if o in [1, 30, 9, 3]:  # use your own logic for change here
        olist[oix]= o +100  # compute your own update value here

print '----\n','After: ',a
=========================================================
which results in this

[ 9:43] C:\pywk\clp>georgehart.py

Before: [0, 1, 2, [20, 30, 40], 9, 3]
----
value  0 is in list [0, 1, 2, [20, 30, 40], 9, 3] at index 0
value  1 is in list [0, 1, 2, [20, 30, 40], 9, 3] at index 1
value  2 is in list [0, 101, 2, [20, 30, 40], 9, 3] at index 2
value 20 is in list [20, 30, 40] at index 0
value 30 is in list [20, 30, 40] at index 1
value 40 is in list [20, 130, 40] at index 2
value  9 is in list [0, 101, 2, [20, 130, 40], 9, 3] at index 4
value  3 is in list [0, 101, 2, [20, 130, 40], 109, 3] at index 5
----
After:  [0, 101, 2, [20, 130, 40], 109, 103]

Regards,
Bengt Richter




More information about the Python-list mailing list