首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最简单的方法来解释字符串:数字,',‘和'-'?

最简单的方法来解释字符串:数字,',‘和'-'?
EN

Stack Overflow用户
提问于 2017-05-18 09:10:01
回答 2查看 19关注 0票数 0

这是一个有点模糊的标题,但我正在编写一个函数,它执行以下操作:

代码语言:javascript
复制
'1,2,3,4' -> [1,2,3,4]  
'1,2-4'   -> [1,2,3,4]  
'1-3,4'   -> [1,2,3,4]  
'1,1,1'   -> [1]  
'3-9, 1'  -> [1,3,4,5,6,7,8,9]  
'4-1,6'   -> [1,2,3,4,6]  

',‘表示前一个数字是完整的,并将其添加到列表中。

'-‘表示将所有数字相加,包括在两边的两个数字之间。

应避免空格,并应忽略重复项

我有一些简陋的python代码,可以让您了解我要做的事情:

代码语言:javascript
复制
def seasons_dict(seasons):

    season_dict = {}

    current = ''
    a = ''
    b = ''
    for i in range(len(seasons)):
        if seasons[i].isdigit():
            current = current + seasons[i]
            if (len(seasons) == (i + 1)) and (current not in season_dict):
                if a == '':
                    season_dict[current] = {}
                    current = ''
                else: 
                    b = current
                    if a == b:
                        season_dict[a] = {}
                        current = ''
                    elif b > a:
                        for s in range(int(a), int(b) + 1):
                            season_dict[str(s)] = {}
                        current = ''
                    elif a > b:
                        for s in range(int(b), int(a) + 1):
                            season_dict[str(s)] = {}
                        current = ''
        elif (seasons[i] == ','):
            if (a == '') and (current not in season_dict):
                season_dict[current] = {}
                current = ''
            elif (a != '') and (current not in season_dict):
                b = current
                if a == b:
                    season_dict[a] = {}
                    current = ''
                elif b > a:
                    for s in range(int(a), int(b) + 1):
                        season_dict[str(s)] = {}
                    current = ''
                elif a > b:
                    for s in range(int(b), int(a) + 1):
                        season_dict[str(s)] = {}
                    current = ''
                a = ''
            else:
                current = ''
        elif seasons[i] == '-':
            a = current
            current = ''

    return season_dict  

是的,我知道我最初说的是list,现在我正在处理字典,但这真的没有什么不同。通常来说,列表更容易思考。

提前感谢大家!如果你有任何问题,请告诉我

EN

回答 2

Stack Overflow用户

发布于 2017-05-18 10:16:42

我认为使用正则表达式来解析你的小迷你语言会让你大大简化代码:

代码语言:javascript
复制
import re

def parse_numbers(num_str):
    results = set()
    for first, second in re.findall(r'(\d+)(?:\s*-\s*(\d+))?', num_str):
        if second:
            if int(first) > int(second):
                first, second = second, first
            results.update(range(int(first), int(second)+1))
        else:
            results.add(int(first)
    return sorted(results)

这可能比您想要的更宽松一些,因为它忽略了不是一个数字或中间有破折号的数字对的任何内容。如果你给它'1,2,foo,3-5',它会很高兴地解析出[1, 2, 3, 4, 5],而忽略foo。如果您担心这一点,您可以编写一个单独的正则表达式来验证输入。同时验证和解析有点困难,所以我会在两个单独的过程中完成。

票数 0
EN

Stack Overflow用户

发布于 2017-05-18 23:46:47

您可以使用集合、排序、解析和范围来执行以下操作:

代码语言:javascript
复制
tests=['1,2,3,4', 
'1,2-4',   
'1-3,4' , 
'1,1,1',   
'3-9, 1',    
'4-1,6',]

for s in tests:
    uniq=set()
    for e in s.split(','):
        if '-' in e:
            t=tuple(map(int, sorted(e.split('-',1))))
            uniq |= set(range(t[0],t[1]+1)) 
        else:
            uniq.add(int(e))
    li=sorted(uniq)

    print("{:10s} -> {}".format(s, li)) 

打印:

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

https://stackoverflow.com/questions/44037044

复制
相关文章

相似问题

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