Making things more functional in Python

Steve Holden steve at holdenweb.com
Fri Mar 4 12:00:38 EST 2005


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
> 
> Namely, I'd like to get rid of the initilization
> (vectors = {}) and also the loop  Yet, I'd hate to put
> an assignment into Python's FP list comprehensions.
> 
> Ideally, I'd like something like this:
> vectors.dict_add({d:result}) for [sample.get_val(d)
> for sample in samples for d in dset].  
> 
> Is there anything like that?  Am I missing the
> picture?
> 
> Thanks.
> 
> PS If possible, please cc me on all responses, thanks.
> 
The logical thing to use would be

return dict([(d, sample.getval(d)) for d in dset for sample in samples])

which (I think) should work from 2.2 onwards.

regards
  Steve
-- 
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005                      http://www.pycon.org/
Steve Holden                           http://www.holdenweb.com/



More information about the Python-list mailing list