min max from tuples in list
Jussi Piitulainen
jpiitula at ling.helsinki.fi
Thu Dec 12 03:52:12 EST 2013
Robert Voigtländer writes:
> Hi,
>
> I have a list like this:
# shortened:
a = [(52, 193), (52, 193), (52, 192),
(51, 193), (51, 191), (51, 190), (51, 189), (51, 188),
(50, 194)]
> I need to find a -performant- way to transform this into a list with
> tuples (a[0],[a[0][1]min],[a[0][1]max]).
>
> Hard to explaint what I mean .. [0] of the first three tuples is
> 52. [1] is 193,193 and 192. What I need as result for these three
> tuples is: (52,192,193).
>
> For the next five tuples it is (51,188,193).
I think you want [(50, 194, 194), (51, 188, 193), (52, 192, 193)] for
the shortened list, in some order. Then you might be happy with a dict
instead. If I misunderstand, the following will be irrelevant.
> Extra challenges:
> - This list is sorted. For performance reasons I would like to keep
> it unsorted.
> - There may be tuples where min=max.
> - There my be tupples where [0] only exists once. So mix is
> automatically max
Scan the list and keep the running min and max for each key in a dict.
mix = dict()
for k,v in a:
mix[k] = ( min(mix.get(k, (v,v))[0], v),
max(mix.get(k, (v,v))[1], v) )
# mix == {50: (194, 194), 51: (188, 193), 52: (192, 193)}
# As list: [ (k,v[0],v[1]) for k,v in mix.items() ]
More information about the Python-list
mailing list