我想不出一个体面的头衔,我为此感到抱歉。我想从用户那里得到一个输入,允许这样的格式(作为字符串):
1, 2,4, 9-13, 12, 3
并为我提供了这样的整数列表:
[1, 2, 3, 4, 9, 10, 11, 12, 13]
我可以想到一些破解这个的可怕方法,我只是想知道是否有什么“好”。我现在正在提交我的第一个想法。
答案 0 :(得分:2)
这是我的"手册"这样做的方式。它可以检查愚蠢,例如:-------1
但如果使用得当它会起作用。
import re
inp = '1, 2,4, 9-13, 12, 3'
ret = []
for g in re.sub(r'[^\d,\-]', '', inp).split(','):
m = re.match('(-?\d+)-(-?\d+)', g)
if not m:
ret.append(int(g))
continue
# we're talking about a range.
a, b = sorted([int(x) for x in m.groups()])
ret += range(a, b+1)
#de-dupe
ret = list(set(ret))
答案 1 :(得分:2)
这样的事情:
from itertools import chain
def solve(s):
for x in s.split(','):
#Strip the trailing and leading spaces + '-' and then split at '-' only once.
d = x.strip(' -').split('-', 1)
if len(d) == 1:
yield [int(d[0])]
elif len(d) == 2:
s, e = sorted(map(int, d))
yield range(s, e+1)
print sorted(set(chain.from_iterable(solve('1--1, 2,4, 9-13, 12, 3'))))
print sorted(set(chain.from_iterable(solve('1, 2,4, 9-14, 12, 3, ------14'))))
print sorted(set(chain.from_iterable(solve('1, 2,4, -----6-----,9-14, 12, 3'))))
print sorted(set(chain.from_iterable(solve('1, 2,4,11--11, -----6-----,9-14, 12, 3'))))
<强>输出:强>
[-1, 0, 1, 2, 3, 4, 9, 10, 11, 12, 13]
[1, 2, 3, 4, 9, 10, 11, 12, 13, 14]
[1, 2, 3, 4, 6, 9, 10, 11, 12, 13, 14]
[-11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]