Python list USES the example list to find consecutive Numbers

  • 2020-04-02 13:25:32
  • OfStack

There is a requirement on the line, format, from a pile of s1,s100-s199 to find the continuous service and format display, such as:

Ghost: S106-109, s123, s125
Royal sword: s106-109, s123, s125


#!/usr/bin/env python
# -*- coding: utf-8 -*- 
#  2014/01/15 14:15
import sys
from itertools import *
from operator import itemgetter
def parse(filename):
    d = {}
    for line in open(filename, 'r'):
        _line = line.split()
        d.setdefault(_line[0], []).append(_line[1])
    for key in d.keys():
        data = sorted(map(lambda x: int(x[1:]), d[key]))
        sys.stdout.write(key + " ")
        for k, g in groupby(enumerate(data), lambda (i, x): i - x):
            ret = map(itemgetter(1), g)
            if len(ret) > 1:
                sys.stdout.write("S%d-%d," % (ret[0], ret[-1]))
            elif len(ret) == 1:
                sys.stdout.write(str("S%s") % ret[0] + ",")
        sys.stdout.write('n')
if __name__ == "__main__":
    filename = sys.argv[1]
    parse(filename)


Related articles: