Making things more functional in Python

Dave Benjamin ramen at lackingtalent.com
Sat Mar 5 08:00:49 CET 2005


On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
> Is there a better, more FP style, more Pythonic way to
> write this:
> 
> def compute_vectors(samples, dset):
> 	vectors = {}
> 	for d in dset:
> 		vectors[d] = [sample.get_val(d) for sample in
> samples]
> 	return vectors

You could use reduce:

def compute_vectors(samples, dset):
    def add_entry(vectors, d):
        vectors[d] = [sample.get_val(d) for sample in samples]
        return vectors
    return reduce(add_entry, dset, {})

Dave





More information about the Python-list mailing list