Saturday, May 22, 2010

[Py] Use ``list comprehensions'' to avoid nesting ``for loops'' too deeply

As I have mentioned in the previous post, I am trying to analyze some data using Python as the programming language. The data sets are from 4 sensor nodes, and each nodes give accelerations in 3 axes. Furthermore, I want to process these data sets in sequential mode. So, the original structure of my program looked like this:

data = zeros((n_nodes,3))

for i in range( len(databuffer) ):
for nodes in range(4):
for xyz in range(3):
data[nodes][xyz] = databuffer[nodes][xyz][i]
if (some conditions):
do something

That's crazy! These nested for loops are too deep to be followed. Also, I remember once I read an article written by an experienced programmer, who said if your for loops nested too deep, then maybe you need to redesign you program.

I had no idea about how to redesign the structure of my program to fit my original requirements. Fortunately, the list comprehensions could resolve this difficulty. Here is the new version using the list comprehensions:

for i in range( len(databuffer[0][0]) ):
data = array([databuffer[nodes][xyz][i]\
for nodes in range(n_nodes) for xyz in range(3)]).reshape(n_nodes,3)
if(some conditions):
do something
The list comprehensions remove two loops and make a conciser new structure.

No comments:

Post a Comment