我有格式化這樣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