Elegant solution needed: Data manipulation
Jason Orendorff
jason at jorendorff.com
Wed Jan 30 20:42:24 EST 2002
Mark wrote:
> Subject: Elegant solution needed: Data manipulation
>
> I have some data: [...]
> I also have an equation:
> add( speed , mul (weight, height) )
>
> I want to read in the equation and perform the corresponding
> operations on the data.
An excellent approach is to write the equation in Python.
Sample code is included below. If you do this, you can even
write your formula like this: "speed + weight * height"
and it will work.
I hope this is clear. Let me know if it isn't.
## Some sample code...
import operator, math
# Step 1. Build your data structure out of objects.
class DataRow:
def __init__(self, height, weight, speed):
self.height = height
self.weight = weight
self.speed = speed
# You can write the part the reads it out of a file.
# Here is what the resulting data structure should be.
data = [ DataRow(3, 6, 12),
DataRow(5, 9, 20),
DataRow(4, 10, 15) ]
# Step 2. Decide which operations you will support.
my_builtins = {
'add': operator.add,
'mul': operator.mul,
'sin': math.sin,
# ...whatever functions you like here...
}
my_globals = { '__builtins__' : my_builtins }
# Step 3. Compile the formula.
formula = "add( speed , mul (weight, height) )"
formula_code = compile(formula, "filename", "eval")
# Step 4. Use eval() and the code object
# to calculate the formula.
for row in data:
# Supply the values defined in the row
# to the formula, as local variables.
my_locals = vars(row)
result = eval(formula_code, my_globals, my_locals)
print result
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list