我在 python 中有一些整数列表:
[[2, 8, 10, 500, 502], [1, 4, 5, 401]]
如何根据列表中数字之间的差异将值扩展为连续范围,这样我会得到如下结果:
[[2, 3, 4, 5, 6, 7, 8, 9, 10, 500, 501, 502], [1, 2, 3, 4, 5, 401]]
那么,基本上,只有当列表中的项目之间的差异小于 100 时,才将一组数字扩展为完整范围?
虽然很丑,但试试这个:
def list_expand(x): new_list = [] while True: if len(x) < 2: new_list.append(x[0]) break m = min(x) x.remove(m) if abs(m - min(x)) < 100: new_list.extend(range(m, min(x))) else: new_list.append(m) return new_list
它通过了这些测试:
assert list_expand([99, 0, 198]) == range(0, 199) assert list_expand([100, 0, 200]) == [0, 100, 200] assert list_expand([2, 8, 10, 500, 502]) == range(2, 11) + range(500, 503) assert list_expand([1, 4, 5, 401]) == range(1, 6) + [401]