This article mainly introduces the list to find continuous numbers in the example, you refer to use it online have a demand, format, from a pile of s1, s100-s199 to find continuous server and format the display, for example:
Magic: S106-109, s123, s125
Royal sword: s106-109, s123, s125
The code is as follows:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
#
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)