6
\$\begingroup\$

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]
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Can you describe what you think is not smooth about this code? It is only 12 lines and is already fairly terse with liberal use of list comprehension. \$\endgroup\$ Commented Feb 4, 2014 at 14:56
  • 2
    \$\begingroup\$ Can you explain what this code is supposed to do? \$\endgroup\$ Commented Feb 4, 2014 at 14:56
  • \$\begingroup\$ @unholysampler: Well, I feel that this c++-type for loops are not really the python way. \$\endgroup\$ Commented Feb 4, 2014 at 15:30
  • \$\begingroup\$ @GarethRees: It is supposed to prepare data for a contour plot with matplotlib. Data is saved as textfiles with format omega-f(omega,p) in different files for different ps. \$\endgroup\$ Commented Feb 4, 2014 at 15:31

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.