2013-12-18 69 views
4

我需要解析描述一組數字的字符串。數字按順序列出,但連續數字的範圍可以使用連字符/短劃線縮寫爲「範圍」。展開描述一組數字和/或範圍的字符串

例:「001,008-011,020

我想解釋這串這是一個有序列表:[ 1, 8, 9, 10, 11, 20 ]

可能有範圍和元素的任意數量。

+4

你有問題嗎?你自己試過這個嗎?你想到了什麼? – Floris

回答

4

你可以做類似下面..

>>> def findval(str): 
...  val = [] 
...  for x in str.split(','): 
...   if '-' in x: 
...   lnum, rnum = x.split('-') 
...   lnum, rnum = int(lnum), int(rnum) 
...   val.extend(range(lnum, rnum + 1)) 
...   else: 
...   lnum = int(x) 
...   val.append(lnum) 
...  return val 

>>> findval('001,008-011,020') 
[1, 8, 9, 10, 11, 20] 

Working demo

+0

謝謝你的快速回答和演示。 – user2724383

3

實現像這樣,拍攝的範圍,並根據整數值迭代:

str = "001,008-011,020" 
spl = str.split(",") 
output = [] 
for s in spl: 
    if '-' in s: 
     rng = s.split(r"-") 
     for r in range(int(rng[0]), int(rng[1])+1): 
      output.append(r) 
    else: 
     output.append(int(s)) 

print output 

打印:

[1, 8, 9, 10, 11, 20] 
+0

你錯過了一個範圍內的最後一個數字,我想你想要int(rng [1])+ 1,否則你只是得到8,9,10的範圍008-011 – Ffisegydd

+0

下面有一個問題,但我把它移到了範圍內。 – brandonscript

4

如果您知道該字符串將永遠在該格式.. 。

x = "001,008-011,020" 

x = x.split(',') # Split at the commas 

y = [] 

# Iterate over the list 
for i in x: 
    try: 
     # Will append the integer to your output list 
     y.append(int(i)) 
    except ValueError: 
     # If you get a ValueError (from trying to int('008-011') for example) 
     # then split the string at the hyphen and individually append 
     # the integers in between. 
     j = i.split('-') 
     for k in range(int(j[0]), int(j[1])+1): 
      y.append(k) 

我認爲應該可以工作,儘管你可能想檢查沒有其他的ValueErrors將被無意中捕獲到try/except循環中。

3

如何:

def expand(s): 
    parts = (map(int, x.split('-')) for x in s.split(',')) 
    return (n for p in parts for n in range(p[0], p[-1]+1)) 

之後

>>> expand("001") 
<generator object <genexpr> at 0x901b784> 
>>> list(expand("001")) 
[1] 
>>> list(expand("001,008-011,020")) 
[1, 8, 9, 10, 11, 20] 
+0

好的和簡短的回答(但不是很清楚內嵌for循環)。 – user2724383