首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用"-“合并编号(python)

使用"-“合并编号(python)
EN

Stack Overflow用户
提问于 2015-03-13 08:07:28
回答 1查看 82关注 0票数 1

这是蟒蛇

代码语言:javascript
运行
复制
temp_list=['1','2','3','5','7','8']
temp_list.sort()
print temp_list
test=""
first=""
last=""
start=0
for i in range(len(temp_list)):
    if i==0:
        None
    else:
        if (int(temp_list[i-1])+1)==int(temp_list[i]):
            print temp_list[i-1]
            print temp_list[i]
            if start==0:
                first=temp_list[i-1]
                last=temp_list[i]
                start=1;
            else:
                last=temp_list[i]
            if len(temp_list)==i+1:
                if start==0:
                    test+=(temp_list[i-1]+","+temp_list[i])
                else:
                    if len(test)!=0:#add
                        test+=(","+first+"-"+last)
                        start=0
                    else:
                        test+=(first+"-"+last)
                        start=0
        else:
            if start==0:
                test+=(temp_list[i-1]+","+temp_list[i])
            else:
                if len(test)!=0:#add
                    test+=(","+first+"-"+last)
                    start=0
                else:
                    test+=(first+"-"+last)
                    start=0
print test

这是示例代码结果-> 1-35,7,7-8

我想转换下面的数字集:

( ex1) '1','2','3','5','7','8‘-> 1-3,5,7-8

( ex2) '0','2','3','4','5','7','8‘-> 0,2-5,7-8

请帮助我的大脑

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-13 08:27:24

这应该是可行的:

代码语言:javascript
运行
复制
def ints_to_ranges(l):
    if not l: return ""

    l = sorted(set(int(n) for n in l))
    ranges = [[l[0], l[0]]]

    for n in l[1:]:
       if n - 1 == ranges[-1][1]:
           ranges[-1][1] += 1
       else:
           ranges.append([n, n])

    return ",".join(r[0] == r[1] and str(r[0]) or "{}-{}".format(*r) for r in ranges)

它的工作方式是删除重复的数字,对它们进行排序,在它们之外构建一个范围列表,然后格式化它们。示例:

代码语言:javascript
运行
复制
>>> ints_to_ranges(['1', '2', '3', '5', '7', '8'])
'1-3,5,7-8'
>>> ints_to_ranges(['0', '2', '3', '4', '5', '7', '8'])
'0,2-5,7-8'
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29027454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档