我有格式化这样numberseries一个长长的清单:我怎样才能轻松处理括号括起来的数字?
["4450[0-9]", "6148[0-9][0-9]"]
我想从那些系列单号码之一做一个清单:
[44500,44501,..., 44509]
我需要为多个系列做到这一点在原始列表内,我想知道做这件事的最好方法是什么?
我有格式化这样numberseries一个长长的清单:我怎样才能轻松处理括号括起来的数字?
["4450[0-9]", "6148[0-9][0-9]"]
我想从那些系列单号码之一做一个清单:
[44500,44501,..., 44509]
我需要为多个系列做到这一点在原始列表内,我想知道做这件事的最好方法是什么?
可能不是最好的解决办法,但你可以接近它递归地寻找[x-y]
范围和generating值(在这种情况下,使用yield
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
可能比我的解决方案更好:P明显好思考与yeild:P –
@JoranBeasley谢谢,我喜欢你认为它的方式作为“反转”:) – alecxe
哈哈是公平的RE是非常严格定义在这里:P为只匹配问题陈述 –
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]")))
Im相当肯定这将工作...但真的,你应该自己尝试一下正在添加的东西来之前...
发现这个模块似乎做我想做的。
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的答案仍然是“最好的”的答案,而不是一个快捷寿
我希望有,做这个,而不是我的潜水深入到正则表达式或诸如此类的东西一些Python模块 – sousys