Custom Search

Sunday, May 1, 2011

Python list comprehensions Tricks

The power of the inline loops.

Suppose we have three-dimensional array:
d3 = [ [ [101,100], [99,98] ] , [ [97,96], [95,94] ] ]

Let's transform it into two-dimensional array
d2 = [ d3[a][b] for a in range(2) for b in range(len(d3)) ]
Result:
[[101, 100], [99, 98], [97, 96], [95, 94]]

and into one-dimensional array:
d1 = [ d2[b][a] for b in range(len(d2)) for a in range(2) ]
Result:
[101, 100, 99, 98, 97, 96, 95, 94]

We can also jump from 3d to 1d:
d1 = [ d3[a][b][c] for a in range(len(d3)) for b in range(2) for c in range(2) ]
Result:
[101, 100, 99, 98, 97, 96, 95, 94]

Now, let's do reverse transformation:
From 1d to 2d:
d2 = [ [ d1[a+b] for b in range(2) ] for a in range(0,len(d1),2) ]
Result:
[[101, 100], [99, 98], [97, 96], [95, 94]]

and from 2d to 3d:
d3 = [ [ d2[a+b] for b in range(2) ] for a in range(0,3,2) ]
Result:
[[[101, 100], [99, 98]], [[97, 96], [95, 94]]]

And of course we can do far-jump from 1d to 3d:
d3 = [ [ [ d1[b+a+c] for c in range(2) ] for b in range(0,3,2) ] for a in range(0,5,4)]
Result:
[[[101, 100], [99, 98]], [[97, 96], [95, 94]]]

No comments:

Post a Comment