Making things more functional in Python
Michael Hoffman
cam.ac.uk at mh391.invalid
Fri Mar 4 11:49:37 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
Generate the whole dictionary on the fly with a Python 2.4 generator
expression:
dict((d, [sample.get_val(d) for sample in samples]) for d in dset)
Whether this is "better" or not I think mainly hinges on which
one you ahve an easier time understanding later. Personally I would
prefer this version, but it's easy to get carried away trying to
functionalize things to the point that a procedural version is much
easier to understand.
> Yet, I'd hate to put an assignment into Python's FP list
> comprehensions.
Indeed it's not possible to have an assignment in a list comprehension.
(Unless it's a side-effect due to a function called by the list
comprehension.)
> 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].
You can't use the name "vectors" without first initializing it
somehow!
--
Michael Hoffman
More information about the Python-list
mailing list