On 04/08/12 16:58, Alonzo Quijote wrote:
Is there a way to define a function which takes
    a list (of lists),
    a position specified by a list of integers [i0,i1,...,in], and
    a value
and returns the result of setting
     list[i0][i1]...[in]=value


Yes it is possible, but if you need this, you should strongly consider rearranging your data so it is easier to work with.

But, for what it's worth, try this:


def setValueAtPosition(list, pos, value):
    tmp = list
    for i in pos[:-1]:
        tmp = tmp[i]
    tmp[pos[-1]] = value


There's no need to return the list argument, because it changes it in-place.

And here is your example:


py> aa=[1, 2, [3, 4]]
py> setValueAtPosition(aa, [2, 0], 5)
py> aa
[1, 2, [5, 4]]


And a more complicated example:

py> L = [0, 1, 2, [3, 4, [5, 6, [7, [8, 9, 10], 11], 12], 13, 14], 15]
py> setValueAtPosition(L, [3, 2, 2, 1, 0], "Surprise!")
py> L
[0, 1, 2, [3, 4, [5, 6, [7, ['Surprise!', 9, 10], 11], 12], 13, 14], 15]



But really, don't do this. Such a thing is hard to understand, hard to use, hard to maintain, and hard to debug when you have a problem. Try to avoid having deeply nested lists like that, your life will be much simpler.



--
Steven
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to