HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Prepare data for a contour plot with matplotlib

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withmatplotlibdataforplotpreparecontour

Problem

My question concerns the following Python code which is already working. As far as I have seen, there are very elegant solutions of compacting code. Do you have any ideas on how to make the following code look smoother?

mom = [0.,0.13,0.27,0.53,0.67]
strings = ['overview_files/root/file_' + str(e) for e in mom] 
myfile = [np.loadtxt(s) for s in strings]
nbinp = len(mom)
nbinomega = len(myfile[0][:,0])

x, y, z = (np.empty(nbinp*nbinomega) for i in range(3))
for i in range(nbinomega):
  for j in range(nbinp):
    i_new = i + j*nbinomega
    y[i_new] = myfile[j][i,0] - 1.4
    x[i_new] = mom[j]
    z[i_new] = myfile[j][i,1]

Solution

You may want to follow PEP8 a bit more closely to learn how to write code that is easily understood by most Python developers. Eg. mom = [0.3, 0.13] instead of mom = [0.3,0.13] and four spaces indentation.

Try to be more careful about variable names. I couldn't understand what most of them meant, which is probably because I don't much about the code you're writing. But think about your readers (including you in three months) and wonder what are the best ways to convey information in your variable names. For example, 'myfile' suggest that this is not a collection. And 'my' doesn't provide any useful information.

There's a common idiom in Python to avoid dealing with ranges explicitely: enumerate().

for i, this in enumerate(myfile):
    for j, that in enumerate(myfile[i]):
        i_new = ...
        y[i_new] = ...
        x[i_new] = ...
        z[i_new] = ...


If you often deal with ranges, it will certainly help you at some point.

Code Snippets

for i, this in enumerate(myfile):
    for j, that in enumerate(myfile[i]):
        i_new = ...
        y[i_new] = ...
        x[i_new] = ...
        z[i_new] = ...

Context

StackExchange Code Review Q#40849, answer score: 3

Revisions (0)

No revisions yet.