Make me beautiful (code needs help)

John Hunter jdhunter at nitace.bsd.uchicago.edu
Tue Jul 23 11:44:42 EDT 2002


>>>>> "Mark" == Mark  <Hobbes2176 at yahoo.com> writes:

    Mark> Now, the other problem, is that in general, I want to fill
    Mark> data["new"] with an arbitary function of the values in
    Mark> data["A"].  As a dumb example, I might want to fill
    Mark> data["new"] with copies of the mean (average) of data["A"].
    Mark> So, in some cases, the new values are relative to the
    Mark> current location (ie i and i-1) and in other they are
    Mark> absolute (ie all of them).

    Mark> I can certainly hack through this, but I'm looking for
    Mark> something pretty.  I know python is up to it.

    Mark> Regards, Mark


Well, you can just write the functions you want, design the functions
to operate on lists, and call them.  If you are using python 2.0 or
later, you can use list comprehensions (as Emile's example
demonstrates) 

http://www.python.org/peps/pep-0202.html

Here are some more examples:

def diff(x):
    return [None]+[a-b for b,a in zip(x,x[1:])]

def square(x):
    return [val*val for val in x]

def mean(x):
    return reduce(lambda a,b: a+b, x)/float(len(x))
    
data = {}
data["A"] = [1,2,4,10,50]
data["New1"] = diff(data["A"])
data["New2"] = square(data["A"])
data["New3"] = mean(data["A"])

print data["New1"]
print data["New2"]
print data["New3"]

If you plan to be using large lists and/or performance is an issue,
you should take a look at Numerical Python, which has lots of built in
functions (diff, mean, std, etc...) for operating on lists

 http://www.pfdubois.com/numpy/

Cheers,
John Hunter



More information about the Python-list mailing list