Make me beautiful (code needs help)

Chris Liechti cliechti at gmx.net
Tue Jul 23 11:28:59 EDT 2002


Mark <Hobbes2176 at yahoo.com> wrote in
news:HVd%8.6582$I4.1825 at nwrddc03.gnilink.net: 

> Ok, I have the following data:
> 
> data["A"] = [1,2,4,10,50]
> 
> and I want to get:
> 
> data["new"] = [?, 1, 2, 6, 40]

is there a special reason to store it in a dict? just use a variable "a" 
and "new"... if you need it in a dict, then assign it to a key in the dict 
at the end. that makes your loop faster.
 
> That is, I want to get the successive differences into their proper
> place. I don't care what is in the question mark spot.  I'll figure
> that out later. 
> 
> Here's my current code:
> 
> for i in range(len(data["A"])):
>      try:
>           data["new"].append(data["A"][i] - data["A"][i-1])
>      except OutOfBounds:
>           data["new"].append("?")
> 
> Now, the other problem, is that in general, I want to fill data["new"]
> with an arbitary function of the values in data["A"].  As a dumb
> example, I might want to fill data["new"] with copies of the mean
> (average) of data["A"].  So, in some cases, the new values are
> relative to the current location (ie i and i-1) and in other they are
> absolute (ie all of them). 
> 
> I can certainly hack through this, but I'm looking for something
> pretty.  I know python is up to it.

well, "pretty" is in the eye of the beholder...

differences (maybe use operator.sub, this is for Py2.2):
>>> map(int.__sub__, a+[0], [0]+a)[1:-1]
[1, 2, 6, 40]

you can have that in a list comprehension too:
>>> [a-b for a,b in zip(a+[0], [0]+a)][1:-1]
[1, 2, 6, 40]

mean:
>>> reduce(int.__add__, a)/float(len(a))
13.4

converting to float isn't needed when you use "form __future__ import 
division"

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list