2012-07-20 64 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