2012-07-20 67 views
1

假设我有这个名单:压实范围

a = [('student', '100'), ('student', '101'), 
    ('student', '102'), ('student', '103'), 
    ('student', '104'), ('student', '105'), 
    ('student', '106'), ('student', '120'), 
    ('student', '121'), ('student', '122'), 
    ('student', '123'), ('student', '124'), 
    ('teacher', '21'), ('teacher', '22'), 
    ('teacher', '23'), ('teacher', '24'), 
    ('teacher', '25'), ('teacher', '26'), 
    ('teacher', '27'), ('teacher', '51'), 
    ('teacher', '52'), ('teacher', '53'), 
    ('teacher', '60'), ('Zstudent', '55'), 
    ('Zstudent', '56'), ('Zstudent', '57'), 
    ('Mstudent', '30'), ('Mstudent', '31')] 

我怎么能输出:

student 100-106 120-124 
teacher 22-27 51-53 60 
Zstudent 55-57 
Mstudent 30-31 
+0

'老师22-27 ...'为什么不'21-27'我不明白的逻辑! – Surya 2012-07-20 04:26:09

+0

这是我的错。我输了21. – John 2012-07-20 05:23:07

回答

4

你可以这样做:

>>> [(i, [int(x[1]) for x in j]) for i,j in 
      itertools.groupby(a, key=operator.itemgetter(0))] 
[('student', [100, 101, 102, 103, 104, 105, 106, 120, 121, 122, 123, 124]), 
('teacher', [21, 22, 23, 24, 25, 26, 27, 51, 52, 53, 60]), 
('Zstudent', [55, 56, 57]), 
('Mstudent', [30, 31])] 

所以你可以使用所产生的列表并使用@gnibbler提供的this recipenice code创建范围。

如果数据没有排序,你可以使用基于字典的解决方案(或defauldict):

>>> d = {} 
>>> for k,v in a: 
    d.setdefault(k, []).append(int(v)) 

你只会失去名字的顺序。

+0

这是一个很好的方法来做分组http://stackoverflow.com/a/3430231/174728 – 2012-07-20 05:34:32