圆月山庄资源网 Design By www.vgjia.com

线上有个需求,格式化,从一堆s1,s100-s199中找出连续的服并且格式化显示出来,如:

神魔:S106-109,s123,s125
御剑: 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)

标签:
list,数字

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com