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
4

1 回答 1

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 提供的漂亮代码创建范围。

如果数据未排序,您可以使用基于 dict 的解决方案(或defauldict):

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

您只会丢失名称的顺序。

于 2012-07-20T04:20:27.593 回答