min max from tuples in list

Denis McMahon denismfmcmahon at gmail.com
Thu Dec 12 20:33:46 EST 2013


On Wed, 11 Dec 2013 23:25:53 -0800, Robert Voigtländer wrote:

> I have a list like this:
> 
> a = [(52, 193), ...... (36, 133)]
 
# iterate over the list of tuples
# creates a dictionary n0:[n1a, n1b, n1c ... ]
# from tuples (n0,n1a), (n0,n1b), (n0,n1c) ...

b = {}
for x in a:
    if x[0] in b:
        pass
    else:
        b[x[0]] = []
    if x[1] not in b[x[0]]:
        b[x[0]].append( x[1] )

# iterate over the dictionary
# create the list of result tuples (n0, n1min, n1max) .....

c = [ (x, min(y), max(y) ) for x,y in b.iteritems() ]
print c

There may be a more efficient test for whether b[x[0]] eists than 
trapping keyError.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list