1

我有一长串数字序列,格式如下:

["4450[0-9]", "6148[0-9][0-9]"]

我想从其中一个带有单个数字的系列中列出一个列表:

[44500,44501,..., 44509]

我需要为原始列表中的许多系列执行此操作,我想知道最好的方法是什么?

4

3 回答 3

2

可能不是最好的解决方案,但您可以递归地查找[x-y]范围并生成值(在这种情况下使用yieldand yield from,因此对于 Python 3.3+):

import re

pattern = re.compile(r"\[(\d+)-(\d+)\]")

def get_range(s):
    matches = pattern.search(s)
    if not matches:
        yield int(s)
    else:
        start, end = matches.groups()
        for i in range(int(start), int(end) + 1):
            repl = pattern.sub(str(i), s, 1)
            yield from get_range(repl)


for item in get_range("6148[0-9][0-9]"):
    print(item)

印刷:

614800
614801
...
614898
614899
于 2016-09-15T17:43:28.830 回答
1
def invertRE(x):
    if not x:
        yield []
    else:
       idx = 1 if not x.startswith("[") else x.index("]") + 1
       for rest in invertRE(x[idx:]):
           if x.startswith("["):
               v1,v2 = map(int,x[1:idx-1].split("-"))
               for i in range(v1,v2+1):
                  yield [str(i),]+rest
           else:
               yield [x[0],] + rest

print(map("".join,invertRE("123[4-7][7-8]")))

我很确定这会奏效......但真的你应该在来这里之前自己尝试一些东西......

于 2016-09-15T17:43:18.813 回答
0

找到了这个模块,它似乎可以满足我的要求。

https://pypi.python.org/pypi/braceexpand/0.1.1

>>> from braceexpand import braceexpand
>>> s = "1[0-2]"
>>> ss = "1[0-2][0-9]"
>>> list(braceexpand(s.replace("[", "{").replace("-","..").replace("]","}")))
['10', '11', '12']
>>> list(braceexpand(ss.replace("[", "{").replace("-","..").replace("]","}")))
['100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129']

alecxe 的答案仍然是“最佳”答案,而不是捷径

于 2016-09-16T11:29:04.077 回答