Hi all, I am looking at neat ways of re writing this code below, especially the for loops as I would have over 50 of these statements if I did this the manual way shown below.

n = 50

files = [open("files%i.txt" % i, "w") for i in range (n)]

for w,x,y,z in zip(ar1.values, br1.values, ar0.values, br0.values):
    val = (sqrt((w.data**2)+(x.data**2)))-(sqrt((y.data**2)+(z.data**2)))
    files[0].write(('%6.20f\n') % (val))

for w,x,y,z in zip(ar2.values, br2.values, ar1.values, br1.values):
    val = (sqrt((w.data**2)+(x.data**2)))-(sqrt((y.data**2)+(z.data**2)))
    files[1].write(('%6.20f\n') % (val))

for w,x,y,z in zip(ar3.values, br3.values, ar2.values, br2.values):
    val = (sqrt((w.data**2)+(x.data**2)))-(sqrt((y.data**2)+(z.data**2)))
    files[2].write(('%6.20f\n') % (val))

Ideally, I would like an option which would use arrays as then I can then call specific data from the array index number.

Thanks for your help!

Can you put all the zipped values into its own list.

allvalues=[zip(ar1.values, br1.values, ar0.values, br0.values), zip(ar2.values, br2.values, ar1.values, br1.values) ... etc]

Then iterate over just this:

for zippedvals in allvalues:
   for w,x,y,z in zippedvals:
        val = (sqrt((w.data**2)+(x.data**2)))-(sqrt((y.data**2)+(z.data**2)))
        files[0].write(('%6.20f\n') % (val))

You can go one step further and write

for i in range(3):
   for w,x,y,z in zip(*(v.values for v in (ar[i+1], br[i+1], ar[i], br[i]))):
        val = (sqrt((w.data**2)+(x.data**2)))-(sqrt((y.data**2)+(z.data**2)))
        files[i].write(('%6.20f\n') % (val))

provided you define lists ar and br containing [ar0, ar1, ar2, ar3] etc instead of variables whith numbered names.

Edited 4 Years Ago by Gribouillis

This article has been dead for over six months. Start a new discussion instead.