3

I using python to generate some POVray rendering code for visualization of some computed data. I need pass a lot parameters from python to strings of POVray code. I would like to make the scrips cleaner. So I would like to use tuples and arrays directly as arguments for string formating. Something like this:

sign   = -1
name   = "temp1"
nu     = 0.245 
boxMin =(0.01,0.01,0.01)  # tuple
boxMax =array([0.99,0.99,0.99]) # array
povfile.write( '''
isosurface {
    function     {  %f*( %f - data3d_%s(x,y,z) )  }
    contained_by { box { <%f,%f,%f>,<%f,%f,%f> } }
}''' %(  sign, nu, name, *boxMin, *boxMax ) )

instead of this:

povfile.write( '''
isosurface {
    function     {  %f*( %f - data3d_%s(x,y,z) )  }
    contained_by { box { <%f,%f,%f>,<%f,%f,%f> } }
}''' %(  sign, nu, name, boxMin[0],boxMin[1],boxMin[2], boxMax[0],boxMax[1],boxMax[2] ) )
Prokop Hapala
  • 2,424
  • 2
  • 30
  • 59

1 Answers1

1

supposing that every element you want to write in your string is a list (or iterable) - even if it is constituted by just one element - then you can use a workaround based on list flattening.

Consider this

flatten_list = lambda tupleOfTuples : [element for tupl in tupleOfTuples for element in tupl]

a = ['hi',]
b = [23,56]
c = ['bye',33,35]

"{0} {1} {2} {3} {4} {5}".format(*flatten_list([a,b,c]))

result

'hi 23 56 bye 33 35'

You can use smarter algorithms to flatten the argument list so to include also non-iterable elements (i.e. the ones constituted by just one item). (see e.g. this answer).

Community
  • 1
  • 1
Acorbe
  • 8,367
  • 5
  • 37
  • 66
  • + 1 for the new style formatting, way more readable than the `%`. If you are working with multidimensional arrays, you can use `np.flatten`. – Davidmh Apr 24 '14 at 09:57