find minimum associated values

Steven Bethard steven.bethard at gmail.com
Fri Jan 25 12:26:29 EST 2008


Alan Isaac wrote:
> I have a small set of objects associated with a larger
> set of values, and I want to map each object to its
> minimum associated value.  The solutions below work,
> but I would like to see prettier solutions...
>
[snip]
>
> # arbitrary setup
> keys = [Pass() for i in range(10)]*3
> vals = [random.random() for i in range(30)]
> kv = zip(keys,vals)
> random.shuffle(kv)
> 
> #OBJECTIVE:
> # find minimum val associated with each "key" in kv
>
[snip]
>
> print "method 3: defaultdict"
> t=time.clock()
> d = defaultdict(list)
> for k,v in kv:
>    d[k].append(v)
> for k in d:
>    d[k] = min(d[k])
> print time.clock()-t
> print d

This is definitely the approach I'd use. Seems "pretty" enough to me. ;-)

STeVe



More information about the Python-list mailing list