如何在python中找到文件的最大和最小数量

时间:2014-04-10 11:52:52

标签: python arrays

我有一个清单:

    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')]

此处N的最低值为7289Z的最低值为238.517,依此类推......

所以,我想在输出中输入这些内容意味着我希望所有NZG分别从此列表中获得最小值和最大值。我不知道该怎么做。对于整数,只有代码是:

#> 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] 

3 个答案:

答案 0 :(得分:3)

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])))

输出:

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

答案 1 :(得分:3)

我的解决方案会更简单一些:

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)

输出应为:

Z 243.363 238.517
G 2.0 0.0
N 7307.0 7289.0

答案 2 :(得分:2)

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])

<强>输出:

G 2
N 7307
Z 243.363