【发布时间】:2026-02-14 00:35:01
【问题描述】:
我想知道是否有任何漂亮/干净的方式来做我想做的事情:)。 (我确定有) 所以我的函数接收一个字符串列表,可以包含两种格式的字符串: “12,13,14,15”或“12 到 15” 目标是解析第二种类型并将“to”替换为区间中的数字。
数字之间的分隔符无关紧要,正则表达式将在之后完成这项工作。 这是伪代码和丑陋的实现
这个想法是用区间中的数字替换列表中的“to”,以便之后我可以使用正则表达式轻松解析数字
# The list is really inconsistent, separators may change and it's hand filled so some comments like in the last example might be present
l = ["12,13,14,15",
"12 to 18",
"10,21,22 to 42",
"14,48,52",
"12,14,22;45 and also 24 to 32"
]
def process_list(l):
for x in l:
if "to" in x:
# Find the 2 numbers around the to and replace the "to" by ",".join(list([interval of number]))
final_list = numero_regex.findall(num)
return final_list
【问题讨论】: