我正在处理一个整数列表,这些整数表示在其中找到关键字的页面。我想构建代码块,将该列表转换为具有特定格式的字符串,并遵循一些简单的规则。单个整数被转换为字符串。连续整数被视为间隔(左界、连字符、右界),然后转换为字符串。每个转换都以逗号分隔。这是输入和预期输出的示例:
input = [4, 5, 6, 7, 8, 9, 10, 22, 23, 26, 62, 63, 113, 137, 138, 139]
expected_output = "4-10, 22, 23, 26, 62, 63, 113, 137-139"
我写了这段代码:
res = [4, 5, 6, 7, 8, 9, 10, 22, 23, 26, 62, 63, 113, 137, 138, 139]
if len(res)>0:
resStr = str(res[0])
isConsecutive = False
for index in range(1, len(res)):
diff = res[index] - res[index-1]
if diff == 1:
isConsecutive = True
if index == len(res)-1:
resStr = resStr + "-" + str(res[index])
continue
else:
if isConsecutive:
isConsecutive = False
resStr = resStr + "-" + str(res[index-1]) + ", " + str(res[index])
else:
resStr = resStr + ", " + str(res[index])
print(res)
print(resStr)
这段代码给了我结果:
4-10, 22-23, 26, 62-63, 113, 137-139
它不认识到只有两个连续的数字不被视为区间:“22, 23”而不是“22-23”,以及“62, 63”而不是“62-63”。 如何解决这个问题?有没有更简单或更有效的方法来执行转换?
您需要跟踪连续数字的数量,并相应地添加规则。
您可以通过使用以下方式来实现这一点
res = [4, 5, 6, 7, 8, 9, 10, 22, 23, 26, 62, 63, 113, 137, 138, 139]
result = []
tmp = []
if len(res) > 0:
for i, v in enumerate(res):
if not tmp:
tmp.append(v)
else:
if v - tmp[-1] == 1:
tmp.append(v)
else:
if len(tmp) > 2:
result.append(f'{tmp[0]}-{tmp[1]}')
else:
result.extend([str(i) for i in tmp])
tmp = [v]
if tmp:
if len(tmp) > 2:
result.append(f'{tmp[0]}-{tmp[1]}')
else:
result.extend([str(i) for i in tmp])
sol = ', '.join(result)
print(sol) # 4-5, 22, 23, 26, 62, 63, 113, 137-138