Elegant solution needed: Data manipulation

Paul Rubin phr-n2002a at nightsong.com
Wed Jan 30 20:05:32 EST 2002


Aristotle_00 at yahoo.com (Mark) writes:
> I can certainly have the data set up as lists in a dictionary so that
> data["height"] will give me [3, 5, 4].  I just need an elegant way to
> parse the equation string and have it apply to the results.  It seems
> pretty easy to convert from add ( x , y) to map( add, x , y) but 1) I
> don't know python's regular expression stuff and 2) it seems there
> should be an even easier way.  I definitely don't want to go as far as
> formally parsing the equation to do this (unless python has some
> killer built in tools).

You could do something like

  data["add"]=lambda x,y: [a[0]+a[1] for a in zip(x,y)]
  data["mul"]=lambda x,y: [a[0]*a[1] for a in zip(x,y)]

  result = eval("add( speed , mul (weight, height) )", data)

but it might be cleaner to design your formula language in a way
that's easier to parse--for example, use a stack-based notation,
like "weight height MUL speed ADD", and then just interpret the
formula straightforwardly.



More information about the Python-list mailing list