generator - Iterate uncleared dimension array in python -
i have multiple dimension array this:
a= [[1,2],[2,4],[31,2]] b= [[[1,2],[2,4],[31,2]],[[22,34],[322,323],[3454,544]]] c= [[[[1,2],[2,4],[31,2]],[[22,34],[322,323],[3454,544]]],[[[1,2],[2,4],[31,2]],[[22,34],[322,323],[3454,544]]]] now want alter value of each [x,y] pair [x,y-x], desired result:
a= [[1,0],[2,2],[31,-29]] ==> [1,0] = [1,(1-0)] i tried utilize generator this(inspired answer):
def flatten(ary): el in ary: if isinstance(el, int): yield ary else: sub in flatten(el): yield sub but not work expected.
how prepare it?
note:
the operation transform [x,y] [x,y-x] may changed accordingly, illustration
[x,y] ==> [x,x*y] maybe operation.
so not want hard code operation iteration.
i want this:
for x,y in flatten(ary): homecoming x,y-x then if necessary, alter :
for x,y in flatten(ary): homecoming x,y+x # operation want
i improve martin konecny answer, below code
def flatten(array, operation): i, e in enumerate(array): if isinstance(e, (list, tuple)) , isinstance(e[0], (list, tuple)): flatten(e, operation) elif isinstance(e, (int, float)): array[0], array[1] = operation(array[0], array[1]) break else: array[i] = operation(e[0], e[1]) a= [[1,2],[2,4],[31,2]] b= [[[1,2],[2,4],[31,2]],[[22,34],[322,323],[3454,544]]] c= [[[[1,2],[2,4],[31,2]],[[22,34],[322,323],[3454,544]]],[[[1,2],[2,4],[31,2]],[[22,34],[322,323],[3454,544]]]] and result of demo:
>>> >>> flatten(a, lambda x, y: [x, y * x]) >>> [[1, 2], [2, 8], [31, 62]] >>> flatten(b, lambda x, y: [x, y - x]) >>> b [[[1, 1], [2, 2], [31, -29]], [[22, 12], [322, 1], [3454, -2910]]] >>> flatten(c, lambda x, y: [x, y + x]) >>> c [[[[1, 3], [2, 6], [31, 33]], [[22, 56], [322, 645], [3454, 3998]]], [[[1, 3], [2, 6], [31, 33]], [[22, 56], [322, 645], [3454, 3998]]]] >>> this new test:
>>> >>> d = [1,2] >>> flatten(d, lambda x, y: [x, y +5]) >>> d [1, 7] >>> hopes, can help you.
python generator
No comments:
Post a Comment