Pythonlist use the example list to find consecutive numbers

Source: Internet
Author: User
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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.