这是一个有点模糊的标题,但我正在编写一个函数,它执行以下操作:
'1,2,3,4' -> [1,2,3,4]
'1,2-4' -> [1,2,3,4]
'1-3,4' -> [1,2,3,4]
'1,1,1' -> [1]
'3-9, 1' -> [1,3,4,5,6,7,8,9]
'4-1,6' -> [1,2,3,4,6] ',‘表示前一个数字是完整的,并将其添加到列表中。
'-‘表示将所有数字相加,包括在两边的两个数字之间。
应避免空格,并应忽略重复项
我有一些简陋的python代码,可以让您了解我要做的事情:
def seasons_dict(seasons):
season_dict = {}
current = ''
a = ''
b = ''
for i in range(len(seasons)):
if seasons[i].isdigit():
current = current + seasons[i]
if (len(seasons) == (i + 1)) and (current not in season_dict):
if a == '':
season_dict[current] = {}
current = ''
else:
b = current
if a == b:
season_dict[a] = {}
current = ''
elif b > a:
for s in range(int(a), int(b) + 1):
season_dict[str(s)] = {}
current = ''
elif a > b:
for s in range(int(b), int(a) + 1):
season_dict[str(s)] = {}
current = ''
elif (seasons[i] == ','):
if (a == '') and (current not in season_dict):
season_dict[current] = {}
current = ''
elif (a != '') and (current not in season_dict):
b = current
if a == b:
season_dict[a] = {}
current = ''
elif b > a:
for s in range(int(a), int(b) + 1):
season_dict[str(s)] = {}
current = ''
elif a > b:
for s in range(int(b), int(a) + 1):
season_dict[str(s)] = {}
current = ''
a = ''
else:
current = ''
elif seasons[i] == '-':
a = current
current = ''
return season_dict 是的,我知道我最初说的是list,现在我正在处理字典,但这真的没有什么不同。通常来说,列表更容易思考。
提前感谢大家!如果你有任何问题,请告诉我
发布于 2017-05-18 10:16:42
我认为使用正则表达式来解析你的小迷你语言会让你大大简化代码:
import re
def parse_numbers(num_str):
results = set()
for first, second in re.findall(r'(\d+)(?:\s*-\s*(\d+))?', num_str):
if second:
if int(first) > int(second):
first, second = second, first
results.update(range(int(first), int(second)+1))
else:
results.add(int(first)
return sorted(results)这可能比您想要的更宽松一些,因为它忽略了不是一个数字或中间有破折号的数字对的任何内容。如果你给它'1,2,foo,3-5',它会很高兴地解析出[1, 2, 3, 4, 5],而忽略foo。如果您担心这一点,您可以编写一个单独的正则表达式来验证输入。同时验证和解析有点困难,所以我会在两个单独的过程中完成。
发布于 2017-05-18 23:46:47
您可以使用集合、排序、解析和范围来执行以下操作:
tests=['1,2,3,4',
'1,2-4',
'1-3,4' ,
'1,1,1',
'3-9, 1',
'4-1,6',]
for s in tests:
uniq=set()
for e in s.split(','):
if '-' in e:
t=tuple(map(int, sorted(e.split('-',1))))
uniq |= set(range(t[0],t[1]+1))
else:
uniq.add(int(e))
li=sorted(uniq)
print("{:10s} -> {}".format(s, li)) 打印:
1,2,3,4 -> [1, 2, 3, 4]
1,2-4 -> [1, 2, 3, 4]
1-3,4 -> [1, 2, 3, 4]
1,1,1 -> [1]
3-9, 1 -> [1, 3, 4, 5, 6, 7, 8, 9]
4-1,6 -> [1, 2, 3, 4, 6]https://stackoverflow.com/questions/44037044
复制相似问题