1

Suppose I have this list:

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

How can I output:

student 100-106 120-124
teacher 22-27 51-53 60
Zstudent 55-57
Mstudent 30-31
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
John
  • 11
  • 1

1 Answers1

4

You can do:

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

so you can use the resulting list and create the ranges using this recipe or the nice code provided by @gnibbler.

If the data isn't sorted, you can use a dict based solution (or defauldict):

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

You will only lose the order of the names.

Community
  • 1
  • 1
JBernardo
  • 32,262
  • 10
  • 90
  • 115