Ruchir
Ruchir

Reputation: 1122

How to find max and min number from a file in python

I have a list :

    a = 
[('N', '7289'), ('N', '7290'), ('N', '7291'), ('N', '7292'), ('N', '7293'), ('N', '7294'), ('N', '7295'), ('N', '7296'), ('N', '7297'), ('N', '7298'), ('N', '7299'),
 ('N', '7300'),('N', '7304'), ('N', '7305'), ('Z', '238.517'), ('N', '7306'),
 ('Z', '243.363'), ('N', '7307'), ('G', '0'), ('G','1'),('G','2')]

Here minimum for N is 7289, for Z it is 238.517, and so on...

So, I want these in my output means I want minimum and maximum from this list for all N, Z and G separately. I have no idea how to do it. For integers only the code is :

#> a = [(1,3),(2,5),(2,4),(7,5)]
#> zip(*a)
[(1, 2, 2, 7), (3, 5, 4, 5)]

#> map(max, zip(*a))
[7, 5] 

#> map(min,zip(*a))
[1, 3] 

Upvotes: 2

Views: 202

Answers (3)

vaultah
vaultah

Reputation: 46573

from itertools import groupby
from operator import itemgetter

a = [('N', '7289'), ('N', '7290'), ('N', '7291'), ('N', '7292'), 
     ('N', '7293'), ('N', '7294'), ('N', '7295'), ('N', '7296'), 
     ('N', '7297'), ('N', '7298'), ('N', '7299'), ('N', '7300'), 
     ('N', '7304'), ('N', '7305'), ('Z', '238.517'), ('N', '7306'), 
     ('Z', '243.363'), ('N', '7307'), ('G', '0'), ('G','1'),('G','2')]

a.sort()
for k, g in groupby(a, key=itemgetter(0)):
    print(max(g, key=lambda x: float(x[1])))

Output:

('G', '2')
('N', '7307')
('Z', '243.363')

Upvotes: 3

logc
logc

Reputation: 3923

My solution would be a bit simpler:

from collections import defaultdict

a = [('N', '7289'),
     #...
     ('G', '2')]

groups = defaultdict(list)
for tupl in a:
    key, value = tupl[0], float(tupl[1])
    groups[key].append(value)

for key, values in groups.iteritems():
    print key, max(values), min(values)

The output should be:

Z 243.363 238.517
G 2.0 0.0
N 7307.0 7289.0

Upvotes: 3

zhenlohuang
zhenlohuang

Reputation: 69

from itertools import groupby
from operator import itemgetter

a = [('N', '7289'), ('N', '7290'), ('N', '7291'), ('N', '7292'), ('N', '7293'), ('N', '7294'), ('N', '7295'), ('N', '7296'), ('N', '7297'), ('N', '7298'), ('N', '7299'), ('N', '7300'),('N', '7304'), ('N', '7305'), ('Z', '238.517'), ('N', '7306'), ('Z', '243.363'), ('N', '7307'), ('G', '0'), ('G','1'),('G','2')]

a.sort(key=itemgetter(0,1))
for key, group in groupby(a, itemgetter(0)):
    print key, max([x[1] for x in group])

Output:

G 2
N 7307
Z 243.363

Upvotes: 2

Related Questions